content
stringlengths 85
101k
| title
stringlengths 0
150
| question
stringlengths 15
48k
| answers
list | answers_scores
list | non_answers
list | non_answers_scores
list | tags
list | name
stringlengths 35
137
|
---|---|---|---|---|---|---|---|---|
Q:
button 'pay now!' not working for redirect to payment-done view in payment-braintree and django
I am writing an online store based on the Django 3 By Example 3rd Edition book. I encountered a problem with the book's codes in the payment section, I searched the internet and updated some of the codes, but I still have a problem! After filling out the debit card form, when I click on
the "pay now!" button, I am not redirected to the Don page!
process.html
{% extends "shop/base.html" %}
{% block title %} Pay by credit card {% endblock %}
{% block sidenavigation %}
{% endblock %}
{% block content %}
Pay by credit card
<form method="post" autocomplete="off">
{% if braintree_error %}
<div class="alert alert-danger fade in">
<button class="close" data-dismiss="alert">×</button>
{{ braintree_error|safe }}
</div>
{% endif %}
<div class="braintree-notifications"></div>
<div id="braintree-dropin"></div>
<input style="background-color: #0783ca" id="submit-button" class="btn btn-success btn-lg btn-block"
type="button" value="Pay now!"/>
</form>
<script>
var braintree_client_token = "{{ client_token}}";
var button = document.querySelector('#submit-button');
braintree.dropin.create({
authorization: "{{client_token}}",
container: '#braintree-dropin',
card: {
cardholderName: {
required: false
}
}
}, function (createErr, instance) {
button.addEventListener('click', function () {
instance.requestPaymentMethod(function (err, payload) {
$.ajax({
type: 'POST',
url: '{% url "payment:process" %}',
data: {
'paymentMethodNonce': payload.nonce,
'csrfmiddlewaretoken': '{{ csrf_token }}'
}
}).done(function (result) {
//do accordingly
});
});
});
});
</script>
{% endblock %}
process view:
def payment_process(request):
"""The view that processes the payment"""
order_id = request.session.get('order_id')
order = get_object_or_404(Order, id=order_id)
total_cost = order.get_total_cost()
print(f'ORDER=== {order.first_name}')
if request.method == 'POST':
print('---------Post------------')
# retrieve nonce
# retrieve nonce
nonce = request.POST.get('paymentMethodNonce', None)
# # create User
customer_kwargs = {
# "customer_id": order.braintree_id
"first_name": order.first_name,
"last_name": order.last_name,
"email": order.email
}
customer_create = gateway.customer.create(customer_kwargs)
customer_id = customer_create.customer.id
# create and submit transaction
result = gateway.transaction.sale({
'amount': f'{total_cost:.2f}',
'payment_method_nonce': nonce,
'options': {
'submit_for_settlement': True
}
})
print(f'Result----{result}')
if result.is_success:
# mark the order as paid
print(f'------Success----')
order.paid = True
# store the unique transaction id
order.braintree_id = result.transaction.id
order.save()
return redirect('payment:done')
else:
return redirect('payment:canceled')
else:
print('---------Get----------')
# generate token
client_token = gateway.client_token.generate()
return render(
request,
'payment/process.html',
{
'order': order,
'client_token': client_token
}
)
A:
indent the code in the payment_process function
|
button 'pay now!' not working for redirect to payment-done view in payment-braintree and django
|
I am writing an online store based on the Django 3 By Example 3rd Edition book. I encountered a problem with the book's codes in the payment section, I searched the internet and updated some of the codes, but I still have a problem! After filling out the debit card form, when I click on
the "pay now!" button, I am not redirected to the Don page!
process.html
{% extends "shop/base.html" %}
{% block title %} Pay by credit card {% endblock %}
{% block sidenavigation %}
{% endblock %}
{% block content %}
Pay by credit card
<form method="post" autocomplete="off">
{% if braintree_error %}
<div class="alert alert-danger fade in">
<button class="close" data-dismiss="alert">×</button>
{{ braintree_error|safe }}
</div>
{% endif %}
<div class="braintree-notifications"></div>
<div id="braintree-dropin"></div>
<input style="background-color: #0783ca" id="submit-button" class="btn btn-success btn-lg btn-block"
type="button" value="Pay now!"/>
</form>
<script>
var braintree_client_token = "{{ client_token}}";
var button = document.querySelector('#submit-button');
braintree.dropin.create({
authorization: "{{client_token}}",
container: '#braintree-dropin',
card: {
cardholderName: {
required: false
}
}
}, function (createErr, instance) {
button.addEventListener('click', function () {
instance.requestPaymentMethod(function (err, payload) {
$.ajax({
type: 'POST',
url: '{% url "payment:process" %}',
data: {
'paymentMethodNonce': payload.nonce,
'csrfmiddlewaretoken': '{{ csrf_token }}'
}
}).done(function (result) {
//do accordingly
});
});
});
});
</script>
{% endblock %}
process view:
def payment_process(request):
"""The view that processes the payment"""
order_id = request.session.get('order_id')
order = get_object_or_404(Order, id=order_id)
total_cost = order.get_total_cost()
print(f'ORDER=== {order.first_name}')
if request.method == 'POST':
print('---------Post------------')
# retrieve nonce
# retrieve nonce
nonce = request.POST.get('paymentMethodNonce', None)
# # create User
customer_kwargs = {
# "customer_id": order.braintree_id
"first_name": order.first_name,
"last_name": order.last_name,
"email": order.email
}
customer_create = gateway.customer.create(customer_kwargs)
customer_id = customer_create.customer.id
# create and submit transaction
result = gateway.transaction.sale({
'amount': f'{total_cost:.2f}',
'payment_method_nonce': nonce,
'options': {
'submit_for_settlement': True
}
})
print(f'Result----{result}')
if result.is_success:
# mark the order as paid
print(f'------Success----')
order.paid = True
# store the unique transaction id
order.braintree_id = result.transaction.id
order.save()
return redirect('payment:done')
else:
return redirect('payment:canceled')
else:
print('---------Get----------')
# generate token
client_token = gateway.client_token.generate()
return render(
request,
'payment/process.html',
{
'order': order,
'client_token': client_token
}
)
|
[
"indent the code in the payment_process function\n"
] |
[
0
] |
[] |
[] |
[
"django",
"django_forms",
"django_templates",
"django_views",
"python"
] |
stackoverflow_0074581726_django_django_forms_django_templates_django_views_python.txt
|
Q:
getting ('Connection aborted.', OSError(0, 'Error')) in Azure ML
I am unable to load BERT model in Azure ML notebook.
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('all-mpnet-base-v2')
I am getting this error:
File /anaconda/envs/azureml_py38/lib/python3.8/site-packages/requests/sessions.py:645, in Session.send(self, request, **kwargs)
642 start = preferred_clock()
644 # Send the request
--> 645 r = adapter.send(request, **kwargs)
647 # Total elapsed time of the request (approximately)
648 elapsed = preferred_clock() - start
File /anaconda/envs/azureml_py38/lib/python3.8/site-packages/requests/adapters.py:501, in HTTPAdapter.send(self, request, stream, timeout, verify, cert, proxies)
498 raise
500 except (ProtocolError, socket.error) as err:
--> 501 raise ConnectionError(err, request=request)
503 except MaxRetryError as e:
504 if isinstance(e.reason, ConnectTimeoutError):
505 # TODO: Remove this in 3.0.0: see #2811
ConnectionError: ('Connection aborted.', OSError(0, 'Error'))
How can I resolve this?
A:
The problem with this package upgrading and that supports the version of python. There is a chance of upgrading the TLS and SSL version in the app functioning portal.
Check the TLS version and all the certificates.
This is also because of older version. Try to execute the below code block so solve the error.
pip install -U sentence-transformers
|
getting ('Connection aborted.', OSError(0, 'Error')) in Azure ML
|
I am unable to load BERT model in Azure ML notebook.
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('all-mpnet-base-v2')
I am getting this error:
File /anaconda/envs/azureml_py38/lib/python3.8/site-packages/requests/sessions.py:645, in Session.send(self, request, **kwargs)
642 start = preferred_clock()
644 # Send the request
--> 645 r = adapter.send(request, **kwargs)
647 # Total elapsed time of the request (approximately)
648 elapsed = preferred_clock() - start
File /anaconda/envs/azureml_py38/lib/python3.8/site-packages/requests/adapters.py:501, in HTTPAdapter.send(self, request, stream, timeout, verify, cert, proxies)
498 raise
500 except (ProtocolError, socket.error) as err:
--> 501 raise ConnectionError(err, request=request)
503 except MaxRetryError as e:
504 if isinstance(e.reason, ConnectTimeoutError):
505 # TODO: Remove this in 3.0.0: see #2811
ConnectionError: ('Connection aborted.', OSError(0, 'Error'))
How can I resolve this?
|
[
"The problem with this package upgrading and that supports the version of python. There is a chance of upgrading the TLS and SSL version in the app functioning portal.\n\nCheck the TLS version and all the certificates.\nThis is also because of older version. Try to execute the below code block so solve the error.\npip install -U sentence-transformers\n\n"
] |
[
0
] |
[] |
[] |
[
"azure_machine_learning_studio",
"bert_language_model",
"python"
] |
stackoverflow_0074550731_azure_machine_learning_studio_bert_language_model_python.txt
|
Q:
How to make a multiple bar chart?
How to make a bar chart using 'altair' to use the information in a table?
If you need to change the table format is it ok, I want to make a bar chart as below.
(My end goal is to create a bar chart in streamlit.)
Example,
import pandas as pd
import streamlit as st
df = pd.DataFrame([['sst', '100', '1000'],['can','500','600']], columns=['model','0','1'])
st.bar_chart(df, ??)
A:
as step 1 - you need to melt your dataframe, so that it would consist only of 3 columns, model, variable (0/1) and value.
Step 2 - Grouped bar chart - is nothing than 2 individual bar charts for each model, stack together as columns.
Step 3 - final tweaks:
Additional chart configuration to make it look as a single chart:
spacing between 2 columns - here it is 0.
Padding inside each chart - to add some breathing space between models and keeping grid lines at the same time
with a stroke opacity =0 - we remove frames around each chart to keep an impression of a single image.
import pandas as pd
import altair as alt
import streamlit as st
df = pd.DataFrame([['sst', '100', '1000'],['can','500','600']], columns=['model','0','1'])
#transform dataframe
source=pd.melt(df, id_vars=['model'])
chart=alt.Chart(source).mark_bar(strokeWidth=100).encode(
x=alt.X('variable:N', title="", scale=alt.Scale(paddingOuter=0.5)),#paddingOuter - you can play with a space between 2 models
y='value:Q',
color='variable:N',
column=alt.Column('model:N', title="", spacing =0), #spacing =0 removes space between columns, colummn for can and st
).properties( width = 300, height = 300, ).configure_header(labelOrient='bottom').configure_view(
strokeOpacity=0)
st.altair_chart(chart) #, use_container_width=True)
|
How to make a multiple bar chart?
|
How to make a bar chart using 'altair' to use the information in a table?
If you need to change the table format is it ok, I want to make a bar chart as below.
(My end goal is to create a bar chart in streamlit.)
Example,
import pandas as pd
import streamlit as st
df = pd.DataFrame([['sst', '100', '1000'],['can','500','600']], columns=['model','0','1'])
st.bar_chart(df, ??)
|
[
"as step 1 - you need to melt your dataframe, so that it would consist only of 3 columns, model, variable (0/1) and value.\nStep 2 - Grouped bar chart - is nothing than 2 individual bar charts for each model, stack together as columns.\nStep 3 - final tweaks:\nAdditional chart configuration to make it look as a single chart:\n\nspacing between 2 columns - here it is 0.\nPadding inside each chart - to add some breathing space between models and keeping grid lines at the same time\nwith a stroke opacity =0 - we remove frames around each chart to keep an impression of a single image.\n\nimport pandas as pd\nimport altair as alt\nimport streamlit as st\n\ndf = pd.DataFrame([['sst', '100', '1000'],['can','500','600']], columns=['model','0','1'])\n\n#transform dataframe \nsource=pd.melt(df, id_vars=['model'])\n\nchart=alt.Chart(source).mark_bar(strokeWidth=100).encode(\n x=alt.X('variable:N', title=\"\", scale=alt.Scale(paddingOuter=0.5)),#paddingOuter - you can play with a space between 2 models \n y='value:Q',\n color='variable:N',\n column=alt.Column('model:N', title=\"\", spacing =0), #spacing =0 removes space between columns, colummn for can and st \n).properties( width = 300, height = 300, ).configure_header(labelOrient='bottom').configure_view(\n strokeOpacity=0)\n\nst.altair_chart(chart) #, use_container_width=True)\n\n\n"
] |
[
1
] |
[] |
[] |
[
"altair",
"grouped_bar_chart",
"python",
"streamlit"
] |
stackoverflow_0074574486_altair_grouped_bar_chart_python_streamlit.txt
|
Q:
How to select every n-th row in dataframe with condition of previous rows based on daily interval
I have a large dataframe and I need a new column sig with values 0 or 1.
The conditions:
Add value = 1 in 3rd row of each day starting at 08:30, if data in row 3 > data row 2 > data row 1, else 0
Limitations: In the original dataframe the intervals of the seconds in the timestamps are not equal, so you can't go by time intervals. The amount of rows per day varies.
Sample dataframe ( I don't know how to randomize seconds, so the intervals here are equal, also the amount of rows are equal):
import pandas as pd
import numpy as np
pd.set_option('display.max_rows', 500)
np.random.seed(100)
dates = pd.date_range("2022.01.01", "2022.01.31", freq="s")
dates=dates[:-1]
df = pd.DataFrame({'date':dates,
'data':np.random.randint(low=0, high=100, size=len(dates)).tolist()})
df['_date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)
df = df.loc[(df._date.dt.hour == 8) & (df._date.dt.minute == 30) & ((df._date.dt.second >= 0) & (df._date.dt.second <= 10))].head(30)
df.drop(['_date'], axis=1, inplace=True)
data
date
2022-01-01 08:30:00 14
2022-01-01 08:30:01 27
2022-01-01 08:30:02 33
2022-01-01 08:30:03 77
2022-01-01 08:30:04 66
2022-01-01 08:30:05 60
2022-01-01 08:30:06 72
2022-01-01 08:30:07 21
2022-01-01 08:30:08 70
2022-01-01 08:30:09 60
2022-01-01 08:30:10 76
2022-01-02 08:30:00 13
2022-01-02 08:30:01 73
2022-01-02 08:30:02 71
2022-01-02 08:30:03 78
2022-01-02 08:30:04 50
2022-01-02 08:30:05 80
2022-01-02 08:30:06 48
2022-01-02 08:30:07 24
2022-01-02 08:30:08 29
2022-01-02 08:30:09 43
2022-01-02 08:30:10 75
2022-01-03 08:30:00 11
2022-01-03 08:30:01 52
How to accomplish this?
Desired outcome:
data sig
date
2022-01-01 08:30:00 14 0
2022-01-01 08:30:01 27 0
2022-01-01 08:30:02 33 1
2022-01-01 08:30:03 77 0
2022-01-01 08:30:04 66 0
2022-01-01 08:30:05 60 0
2022-01-01 08:30:06 72 0
2022-01-01 08:30:07 21 0
2022-01-01 08:30:08 70 0
2022-01-01 08:30:09 60 0
2022-01-01 08:30:10 76 0
2022-01-02 08:30:00 13 0
2022-01-02 08:30:01 73 0
2022-01-02 08:30:02 71 0
2022-01-02 08:30:03 78 0
2022-01-02 08:30:04 50 0
2022-01-02 08:30:05 80 0
2022-01-02 08:30:06 48 0
2022-01-02 08:30:07 24 0
2022-01-02 08:30:08 29 0
2022-01-02 08:30:09 43 0
2022-01-02 08:30:10 75 0
2022-01-03 08:30:00 11 0
2022-01-03 08:30:01 32 0
2022-01-03 08:30:02 52 1
2022-01-03 08:30:03 44 0
2022-01-03 08:30:03 75 0
A:
I took your code to create the input data, but it looks bit different to the printed version of yours:
data
date
2022-01-01 08:30:00 14
2022-01-01 08:30:01 27
2022-01-01 08:30:02 33
2022-01-01 08:30:03 77
2022-01-01 08:30:04 66
2022-01-01 08:30:05 60
2022-01-01 08:30:06 72
2022-01-01 08:30:07 21
2022-01-01 08:30:08 70
2022-01-01 08:30:09 60
2022-01-01 08:30:10 76
2022-01-02 08:30:00 13
2022-01-02 08:30:01 73
2022-01-02 08:30:02 71
2022-01-02 08:30:03 78
2022-01-02 08:30:04 50
2022-01-02 08:30:05 80
2022-01-02 08:30:06 48
2022-01-02 08:30:07 24
2022-01-02 08:30:08 29
2022-01-02 08:30:09 43
2022-01-02 08:30:10 75
2022-01-03 08:30:00 11
2022-01-03 08:30:01 52
2022-01-03 08:30:02 40
2022-01-03 08:30:03 30
2022-01-03 08:30:04 44
2022-01-03 08:30:05 71
2022-01-03 08:30:06 64
2022-01-03 08:30:07 60
Your rules could be described as well as a rolling window of 3 rows, check if the window is already sorted (value3 bigger than 2 bigger than 1).
Knowing that we could use this condition on the whole data (without paying attention to date) and create a Series with values of 1 if condition is True and 0 for False (named cond)
Then search for the 3rd value of each day and map the value of that index in cond to the new column.
def window_sorted(grp):
return (np.diff(grp) > 0).all()
cond = df['data'].rolling(window=3, min_periods=1).apply(window_sorted)
df['sig'] = 0
grp = df.groupby(pd.Grouper(level=0, freq='D'), as_index=False)['data'].nth(2).index
df.loc[grp, 'sig'] = cond[grp]
print(df)
Output:
data sig
date
2022-01-01 08:30:00 14 0
2022-01-01 08:30:01 27 0
2022-01-01 08:30:02 33 1
2022-01-01 08:30:03 77 0
2022-01-01 08:30:04 66 0
2022-01-01 08:30:05 60 0
2022-01-01 08:30:06 72 0
2022-01-01 08:30:07 21 0
2022-01-01 08:30:08 70 0
2022-01-01 08:30:09 60 0
2022-01-01 08:30:10 76 0
2022-01-02 08:30:00 13 0
2022-01-02 08:30:01 73 0
2022-01-02 08:30:02 71 0
2022-01-02 08:30:03 78 0
2022-01-02 08:30:04 50 0
2022-01-02 08:30:05 80 0
2022-01-02 08:30:06 48 0
2022-01-02 08:30:07 24 0
2022-01-02 08:30:08 29 0
2022-01-02 08:30:09 43 0
2022-01-02 08:30:10 75 0
2022-01-03 08:30:00 11 0
2022-01-03 08:30:01 52 0
2022-01-03 08:30:02 40 0
2022-01-03 08:30:03 30 0
2022-01-03 08:30:04 44 0
2022-01-03 08:30:05 71 0
2022-01-03 08:30:06 64 0
2022-01-03 08:30:07 60 0
|
How to select every n-th row in dataframe with condition of previous rows based on daily interval
|
I have a large dataframe and I need a new column sig with values 0 or 1.
The conditions:
Add value = 1 in 3rd row of each day starting at 08:30, if data in row 3 > data row 2 > data row 1, else 0
Limitations: In the original dataframe the intervals of the seconds in the timestamps are not equal, so you can't go by time intervals. The amount of rows per day varies.
Sample dataframe ( I don't know how to randomize seconds, so the intervals here are equal, also the amount of rows are equal):
import pandas as pd
import numpy as np
pd.set_option('display.max_rows', 500)
np.random.seed(100)
dates = pd.date_range("2022.01.01", "2022.01.31", freq="s")
dates=dates[:-1]
df = pd.DataFrame({'date':dates,
'data':np.random.randint(low=0, high=100, size=len(dates)).tolist()})
df['_date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)
df = df.loc[(df._date.dt.hour == 8) & (df._date.dt.minute == 30) & ((df._date.dt.second >= 0) & (df._date.dt.second <= 10))].head(30)
df.drop(['_date'], axis=1, inplace=True)
data
date
2022-01-01 08:30:00 14
2022-01-01 08:30:01 27
2022-01-01 08:30:02 33
2022-01-01 08:30:03 77
2022-01-01 08:30:04 66
2022-01-01 08:30:05 60
2022-01-01 08:30:06 72
2022-01-01 08:30:07 21
2022-01-01 08:30:08 70
2022-01-01 08:30:09 60
2022-01-01 08:30:10 76
2022-01-02 08:30:00 13
2022-01-02 08:30:01 73
2022-01-02 08:30:02 71
2022-01-02 08:30:03 78
2022-01-02 08:30:04 50
2022-01-02 08:30:05 80
2022-01-02 08:30:06 48
2022-01-02 08:30:07 24
2022-01-02 08:30:08 29
2022-01-02 08:30:09 43
2022-01-02 08:30:10 75
2022-01-03 08:30:00 11
2022-01-03 08:30:01 52
How to accomplish this?
Desired outcome:
data sig
date
2022-01-01 08:30:00 14 0
2022-01-01 08:30:01 27 0
2022-01-01 08:30:02 33 1
2022-01-01 08:30:03 77 0
2022-01-01 08:30:04 66 0
2022-01-01 08:30:05 60 0
2022-01-01 08:30:06 72 0
2022-01-01 08:30:07 21 0
2022-01-01 08:30:08 70 0
2022-01-01 08:30:09 60 0
2022-01-01 08:30:10 76 0
2022-01-02 08:30:00 13 0
2022-01-02 08:30:01 73 0
2022-01-02 08:30:02 71 0
2022-01-02 08:30:03 78 0
2022-01-02 08:30:04 50 0
2022-01-02 08:30:05 80 0
2022-01-02 08:30:06 48 0
2022-01-02 08:30:07 24 0
2022-01-02 08:30:08 29 0
2022-01-02 08:30:09 43 0
2022-01-02 08:30:10 75 0
2022-01-03 08:30:00 11 0
2022-01-03 08:30:01 32 0
2022-01-03 08:30:02 52 1
2022-01-03 08:30:03 44 0
2022-01-03 08:30:03 75 0
|
[
"I took your code to create the input data, but it looks bit different to the printed version of yours:\n data\ndate \n2022-01-01 08:30:00 14\n2022-01-01 08:30:01 27\n2022-01-01 08:30:02 33\n2022-01-01 08:30:03 77\n2022-01-01 08:30:04 66\n2022-01-01 08:30:05 60\n2022-01-01 08:30:06 72\n2022-01-01 08:30:07 21\n2022-01-01 08:30:08 70\n2022-01-01 08:30:09 60\n2022-01-01 08:30:10 76\n2022-01-02 08:30:00 13\n2022-01-02 08:30:01 73\n2022-01-02 08:30:02 71\n2022-01-02 08:30:03 78\n2022-01-02 08:30:04 50\n2022-01-02 08:30:05 80\n2022-01-02 08:30:06 48\n2022-01-02 08:30:07 24\n2022-01-02 08:30:08 29\n2022-01-02 08:30:09 43\n2022-01-02 08:30:10 75\n2022-01-03 08:30:00 11\n2022-01-03 08:30:01 52\n2022-01-03 08:30:02 40\n2022-01-03 08:30:03 30\n2022-01-03 08:30:04 44\n2022-01-03 08:30:05 71\n2022-01-03 08:30:06 64\n2022-01-03 08:30:07 60\n\nYour rules could be described as well as a rolling window of 3 rows, check if the window is already sorted (value3 bigger than 2 bigger than 1).\nKnowing that we could use this condition on the whole data (without paying attention to date) and create a Series with values of 1 if condition is True and 0 for False (named cond)\nThen search for the 3rd value of each day and map the value of that index in cond to the new column.\ndef window_sorted(grp):\n return (np.diff(grp) > 0).all()\n\ncond = df['data'].rolling(window=3, min_periods=1).apply(window_sorted)\n\ndf['sig'] = 0\ngrp = df.groupby(pd.Grouper(level=0, freq='D'), as_index=False)['data'].nth(2).index\ndf.loc[grp, 'sig'] = cond[grp]\nprint(df)\n\nOutput:\n data sig\ndate \n2022-01-01 08:30:00 14 0\n2022-01-01 08:30:01 27 0\n2022-01-01 08:30:02 33 1\n2022-01-01 08:30:03 77 0\n2022-01-01 08:30:04 66 0\n2022-01-01 08:30:05 60 0\n2022-01-01 08:30:06 72 0\n2022-01-01 08:30:07 21 0\n2022-01-01 08:30:08 70 0\n2022-01-01 08:30:09 60 0\n2022-01-01 08:30:10 76 0\n2022-01-02 08:30:00 13 0\n2022-01-02 08:30:01 73 0\n2022-01-02 08:30:02 71 0\n2022-01-02 08:30:03 78 0\n2022-01-02 08:30:04 50 0\n2022-01-02 08:30:05 80 0\n2022-01-02 08:30:06 48 0\n2022-01-02 08:30:07 24 0\n2022-01-02 08:30:08 29 0\n2022-01-02 08:30:09 43 0\n2022-01-02 08:30:10 75 0\n2022-01-03 08:30:00 11 0\n2022-01-03 08:30:01 52 0\n2022-01-03 08:30:02 40 0\n2022-01-03 08:30:03 30 0\n2022-01-03 08:30:04 44 0\n2022-01-03 08:30:05 71 0\n2022-01-03 08:30:06 64 0\n2022-01-03 08:30:07 60 0\n\n"
] |
[
1
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074581583_pandas_python.txt
|
Q:
Get Path to Python File Before Installation
I have a project that includes c++ binaries and python scripts, it's setup such that it should be installed using setuptools. One of the python files is intended to be both used as a script "
python3 script_name.py params
and for it's primary function to be used in other python projects from script_name import function.
The primary function calls a binary which is in a known relative location before the installation (the user is expected to call pip install project_folder). So in order to call the binary I want to get this files location (pre installation)
To get this I used something like
Path(__file__).resolve().parent
however, since the installation moves the file to another folder like ~/.local/... this doesn't work when imported after the installation.
Is there a way to get the original file path, or to make the installation save that path somewhere?
EDIT:
After @sinoroc 's suggestion I tried including the binary as a resource by putting an __init__.py in the build folder and putting
from importlib.resources import files
import build
binary = files(build).joinpath("binary")
in the main init. After that package.binary still gives me a path to my .local/lib and binary.is_file() still returns False
from importlib_resources import files
GenerateHistograms = files("build").joinpath("GenerateHistograms")
gave the same result
A:
Since you are installing your package, you also need to include your C++ binary in the installation. You cannot have a mixed setup. I suggest something like this.
In your setup.py:
from setuptools import setup, find_packages
setup(
name="mypkg",
packages=find_packages(exclude=["tests"]),
package_data={
"mypkg": [
"binary", # relative path to your package directory
]
},
include_package_data=True,
)
Then in your module use pkg_resources:
from pathlib import Path
from pkg_resources import resource_filename
# "binary" is whatever relative path you put in package_data
path_to_binary = Path(resource_filename("mypkg", "binary"))
pkg_resources should be pulled in by setuptools.
EDIT: the recipe above might be a bit out of date; as @sinoroc suggests, using importlib.resources instead of pkg_resources is probably the modern equivalent.
A:
So I managed to solve it in with @sinroc 's approach in the end
In setup.py
package_data={'package':['build/*']}
include_package_data=True
and in the primary __init.py__:
from importlib.resources import files
binary = files("package.build").joinpath("binary")
So I could then from package import binary to get the path
EDIT: Looks like someone also pointed the error in my ways out before I finished ^^
|
Get Path to Python File Before Installation
|
I have a project that includes c++ binaries and python scripts, it's setup such that it should be installed using setuptools. One of the python files is intended to be both used as a script "
python3 script_name.py params
and for it's primary function to be used in other python projects from script_name import function.
The primary function calls a binary which is in a known relative location before the installation (the user is expected to call pip install project_folder). So in order to call the binary I want to get this files location (pre installation)
To get this I used something like
Path(__file__).resolve().parent
however, since the installation moves the file to another folder like ~/.local/... this doesn't work when imported after the installation.
Is there a way to get the original file path, or to make the installation save that path somewhere?
EDIT:
After @sinoroc 's suggestion I tried including the binary as a resource by putting an __init__.py in the build folder and putting
from importlib.resources import files
import build
binary = files(build).joinpath("binary")
in the main init. After that package.binary still gives me a path to my .local/lib and binary.is_file() still returns False
from importlib_resources import files
GenerateHistograms = files("build").joinpath("GenerateHistograms")
gave the same result
|
[
"Since you are installing your package, you also need to include your C++ binary in the installation. You cannot have a mixed setup. I suggest something like this.\nIn your setup.py:\nfrom setuptools import setup, find_packages\n\nsetup(\n name=\"mypkg\",\n packages=find_packages(exclude=[\"tests\"]),\n package_data={\n \"mypkg\": [\n \"binary\", # relative path to your package directory\n ]\n },\n include_package_data=True,\n)\n\nThen in your module use pkg_resources:\nfrom pathlib import Path\n\nfrom pkg_resources import resource_filename\n\n# \"binary\" is whatever relative path you put in package_data\npath_to_binary = Path(resource_filename(\"mypkg\", \"binary\"))\n\npkg_resources should be pulled in by setuptools.\nEDIT: the recipe above might be a bit out of date; as @sinoroc suggests, using importlib.resources instead of pkg_resources is probably the modern equivalent.\n",
"So I managed to solve it in with @sinroc 's approach in the end\nIn setup.py\npackage_data={'package':['build/*']}\ninclude_package_data=True\n\nand in the primary __init.py__:\nfrom importlib.resources import files\nbinary = files(\"package.build\").joinpath(\"binary\")\n\nSo I could then from package import binary to get the path\nEDIT: Looks like someone also pointed the error in my ways out before I finished ^^\n"
] |
[
1,
0
] |
[] |
[] |
[
"packaging",
"path",
"pip",
"python",
"setuptools"
] |
stackoverflow_0074577488_packaging_path_pip_python_setuptools.txt
|
Q:
Is it possible to write to multiple coils using pyModbusTCP library
There is a method from the documents that looks like client.write_coils(1, [True]*8)
My assumption is that this will write True 8 times because how do I supply a list of addresses? I want to supply a list of 8 modbuss address and assign them all True, for the sake of example. The alternate way is use the singular write_coil from a loop, but since write_coils exists in the docs I am assuming it is the better solution
A:
I agree that the documentation for write_multiple_coils(addr, values) is ambiguous.
You can look at the Modbus specification for Write Multiple Coils (function code 0x15) which says:
Writes each coil in a sequence of coils to either ON or OFF.
So it might be helpful to think of the address as the starting address. So if your starting address is 1 and values is [1,1,1,1,1,1,1,1], you'll write True to Coils 1 through 8. You could manually iterate through the values if you'd prefer, that's what the example code does.
You can also look at the source code for the function:
One of the error checks also makes this plain:
if int(bits_addr) + len(bits_value) > 0x10000:
raise ValueError('write after end of modbus address space')
If you try to write [1,1,1] to address 0x9999 you'll trigger this exception.
|
Is it possible to write to multiple coils using pyModbusTCP library
|
There is a method from the documents that looks like client.write_coils(1, [True]*8)
My assumption is that this will write True 8 times because how do I supply a list of addresses? I want to supply a list of 8 modbuss address and assign them all True, for the sake of example. The alternate way is use the singular write_coil from a loop, but since write_coils exists in the docs I am assuming it is the better solution
|
[
"I agree that the documentation for write_multiple_coils(addr, values) is ambiguous.\nYou can look at the Modbus specification for Write Multiple Coils (function code 0x15) which says:\n\nWrites each coil in a sequence of coils to either ON or OFF.\n\nSo it might be helpful to think of the address as the starting address. So if your starting address is 1 and values is [1,1,1,1,1,1,1,1], you'll write True to Coils 1 through 8. You could manually iterate through the values if you'd prefer, that's what the example code does.\nYou can also look at the source code for the function:\nOne of the error checks also makes this plain:\nif int(bits_addr) + len(bits_value) > 0x10000:\n raise ValueError('write after end of modbus address space') \n\nIf you try to write [1,1,1] to address 0x9999 you'll trigger this exception.\n"
] |
[
1
] |
[] |
[] |
[
"modbus",
"modbus_tcp",
"pymodbus",
"python",
"tcp"
] |
stackoverflow_0074576917_modbus_modbus_tcp_pymodbus_python_tcp.txt
|
Q:
Load mobile net (keras) in tensorflow.js
I'm trying to load a keras model which is based on mobilen in Tensorflow.js.
Sadly this does not work I generated the model with the following python code
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
import tensorflowjs as tfjs
input_shape = 224,224 #sorry of all lowercase
num_classes = 2
mobile_net = tf.keras.applications.MobileNetV2(
input_shape=input_shape+(3,),
alpha=1.0,
include_top=False,
weights="imagenet",
input_tensor=None,
pooling=None,
classes=2,
classifier_activation="softmax"
)
model = keras.Sequential(
[
keras.Input(shape=input_shape+(3,)),
layers.Rescaling(1./255),
mobile_net,
layers.Flatten(),
layers.Dense(num_classes, activation="softmax")
]
)
model.build((None,)+input_shape+(3,))
tfjs.converters.save_keras_model(model,'./model.json')
print(model.summary())
afterwards I'm trying to load the model in node.js REPL with the following commands
const tf = require('@tensorflow/tfjs')
async function predict(){
const model = await tf.loadLayersModel('file:///./model.json');
}
predict()
however I get the error message.
Uncaught TypeError: fetch failed
at Object.fetch (node:internal/deps/undici/undici:14294:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
cause: Error: not implemented... yet...
at makeNetworkError (node:internal/deps/undici/undici:6789:35)
at schemeFetch (node:internal/deps/undici/undici:13774:18)
at node:internal/deps/undici/undici:13654:26
at mainFetch (node:internal/deps/undici/undici:13671:11)
at fetching (node:internal/deps/undici/undici:13628:7)
at fetch2 (node:internal/deps/undici/undici:13506:20)
at Object.fetch (node:internal/deps/undici/undici:14292:18)
at fetch (node:internal/process/pre_execution:238:25)
at PlatformNode.fetch (/Users/z003cyub/Documents/projects/FY2022/aufsteller/node_modules/@tensorflow/tfjs-core/dist/tf-core.node.js:7542:33)
at HTTPRequest.<anonymous> (/Users/z003cyub/Documents/projects/FY2022/aufsteller/node_modules/@tensorflow/tfjs-core/dist/tf-core.node.js:8406:55) {
[cause]: undefined
I would like to blame it on the model structure, however, I get the same error with a freakingly simple model
model2 = keras.Sequential(
[
keras.Input(shape=input_shape+(3,)),
layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Flatten(),
layers.Dropout(0.5),
layers.Dense(num_classes, activation="softmax"),
]
)
A:
not a layers or a model problem per-say, more of a nodejs problem. latest version of node define global fetch, but implementation is still not complete and it lacks support for file://. and tfjs will use global fetch if its defined. try using node --no-experimental-fetch so global fetch is not defined and tfjs will use internal methods insteads.
|
Load mobile net (keras) in tensorflow.js
|
I'm trying to load a keras model which is based on mobilen in Tensorflow.js.
Sadly this does not work I generated the model with the following python code
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
import tensorflowjs as tfjs
input_shape = 224,224 #sorry of all lowercase
num_classes = 2
mobile_net = tf.keras.applications.MobileNetV2(
input_shape=input_shape+(3,),
alpha=1.0,
include_top=False,
weights="imagenet",
input_tensor=None,
pooling=None,
classes=2,
classifier_activation="softmax"
)
model = keras.Sequential(
[
keras.Input(shape=input_shape+(3,)),
layers.Rescaling(1./255),
mobile_net,
layers.Flatten(),
layers.Dense(num_classes, activation="softmax")
]
)
model.build((None,)+input_shape+(3,))
tfjs.converters.save_keras_model(model,'./model.json')
print(model.summary())
afterwards I'm trying to load the model in node.js REPL with the following commands
const tf = require('@tensorflow/tfjs')
async function predict(){
const model = await tf.loadLayersModel('file:///./model.json');
}
predict()
however I get the error message.
Uncaught TypeError: fetch failed
at Object.fetch (node:internal/deps/undici/undici:14294:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
cause: Error: not implemented... yet...
at makeNetworkError (node:internal/deps/undici/undici:6789:35)
at schemeFetch (node:internal/deps/undici/undici:13774:18)
at node:internal/deps/undici/undici:13654:26
at mainFetch (node:internal/deps/undici/undici:13671:11)
at fetching (node:internal/deps/undici/undici:13628:7)
at fetch2 (node:internal/deps/undici/undici:13506:20)
at Object.fetch (node:internal/deps/undici/undici:14292:18)
at fetch (node:internal/process/pre_execution:238:25)
at PlatformNode.fetch (/Users/z003cyub/Documents/projects/FY2022/aufsteller/node_modules/@tensorflow/tfjs-core/dist/tf-core.node.js:7542:33)
at HTTPRequest.<anonymous> (/Users/z003cyub/Documents/projects/FY2022/aufsteller/node_modules/@tensorflow/tfjs-core/dist/tf-core.node.js:8406:55) {
[cause]: undefined
I would like to blame it on the model structure, however, I get the same error with a freakingly simple model
model2 = keras.Sequential(
[
keras.Input(shape=input_shape+(3,)),
layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
layers.MaxPooling2D(pool_size=(2, 2)),
layers.Flatten(),
layers.Dropout(0.5),
layers.Dense(num_classes, activation="softmax"),
]
)
|
[
"not a layers or a model problem per-say, more of a nodejs problem. latest version of node define global fetch, but implementation is still not complete and it lacks support for file://. and tfjs will use global fetch if its defined. try using node --no-experimental-fetch so global fetch is not defined and tfjs will use internal methods insteads.\n"
] |
[
1
] |
[] |
[] |
[
"keras",
"node.js",
"python",
"tensorflow",
"tensorflow.js"
] |
stackoverflow_0074577573_keras_node.js_python_tensorflow_tensorflow.js.txt
|
Q:
Pandas DataFrame sorting issues, grouping for no reason?
I have one data frame containing stats about NBA season. I'm simply trying to sort by date, but for some reason it's grouping all games that have the same data and changing the values of that said date to the same values.
df = pd.read_csv("gamedata.csv")
df["Total"] = df["Tm"] + df["Opp.1"]
teams = df['Team']
df = df.drop(columns=['Team'])
df.insert(loc=4, column='Team', value=teams)
df["W/L"] = df["W/L"]=="W"
df["W/L"] = df["W/L"].astype(int)
df = df.sort_values("Date")
df.to_csv("gamedata_clean.csv")
Before
After
I expected the df to be unchanged except for the order to be in ascending date, but it's changing values in other columns for reasons I do not know.
A:
Please add this line to your code to sort your dataframe by date
df.sort_values(by='Date')
I hope you will get the desired output
|
Pandas DataFrame sorting issues, grouping for no reason?
|
I have one data frame containing stats about NBA season. I'm simply trying to sort by date, but for some reason it's grouping all games that have the same data and changing the values of that said date to the same values.
df = pd.read_csv("gamedata.csv")
df["Total"] = df["Tm"] + df["Opp.1"]
teams = df['Team']
df = df.drop(columns=['Team'])
df.insert(loc=4, column='Team', value=teams)
df["W/L"] = df["W/L"]=="W"
df["W/L"] = df["W/L"].astype(int)
df = df.sort_values("Date")
df.to_csv("gamedata_clean.csv")
Before
After
I expected the df to be unchanged except for the order to be in ascending date, but it's changing values in other columns for reasons I do not know.
|
[
"Please add this line to your code to sort your dataframe by date\ndf.sort_values(by='Date')\n\nI hope you will get the desired output\n"
] |
[
0
] |
[] |
[] |
[
"data_cleaning",
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074579916_data_cleaning_dataframe_pandas_python.txt
|
Q:
Attribute error when working with 'self' and 'with'
I'm working on a Python script to generate a report in PDF using PyLatex. I set up a class ReportGeneration.
Inside, a table 'overview_table' is defined. When I try to work with table from 2 functions, it gives me the error: AttributeError: args
A small snippet of the init method:
self.doc = Document()
self.doc.documentclass = Command(
'documentclass',
options=['12pt'],
arguments=['article']
)
# Set up preamble (cannot share code)
self.overview_table = self.doc.create(LongTable("| l | l | l |"))
The first function, that works perfectly when called is as follows:
def set_up_overview(self):
with self.doc.create(Section('Overview')):
self.doc.append(Command('centering'))
with self.overview_table as table:
table.add_hline()
table.add_row(bold("Index"), bold("File Name"), bold("Result"))
table.add_hline()
table.end_table_header()
The second function is as follows:
def add_data_to_report(self):
with self.overview_table as overview_table:
overview_table.add_hline()
Calling the second function crashes the program. I've tried searching for similar errors, but the closest I could get was that __enter__ was not defined. I'm not sure how to proceed from there.
The complete error message is
File "/Users/user/IdeaProjects/report/src/reportgen.py", line 46, in add_data_to_report
with self.overview_table as overview_table:
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/contextlib.py", line 133, in __enter__
del self.args, self.kwds, self.func
AttributeError: args
It'll be great help if someone can explain what went wrong. Thanks!
A:
It seems that the pylatex package has used the @contextlib.contextmanager decorator on the create method.
@contextmanager
def create(self, child):
"""Add a LaTeX object to current container, context-manager style.
Args
----
child: `~.Container`
An object to be added to the current container
"""
prev_data = self.data
self.data = child.data # This way append works appends to the child
yield child # allows with ... as to be used as well
self.data = prev_data
self.append(child)
As mentioned in the contextlib documentation,
The function being decorated must return a generator-iterator when called. This iterator must yield exactly one value, which will be bound to the targets in the with statement’s as clause, if any.
This means that you can use the returned value from the create function only once in a context as you have done.
I would recommend you do one of
do everything you want to do with the overview_table inside a single context (that would be inside the initial set_up_overview function in your case)
take a look at the pylatex documentation and see if you can use the values they have set using self.append(child) in the create method
add the yielded object as an attribute on your class
|
Attribute error when working with 'self' and 'with'
|
I'm working on a Python script to generate a report in PDF using PyLatex. I set up a class ReportGeneration.
Inside, a table 'overview_table' is defined. When I try to work with table from 2 functions, it gives me the error: AttributeError: args
A small snippet of the init method:
self.doc = Document()
self.doc.documentclass = Command(
'documentclass',
options=['12pt'],
arguments=['article']
)
# Set up preamble (cannot share code)
self.overview_table = self.doc.create(LongTable("| l | l | l |"))
The first function, that works perfectly when called is as follows:
def set_up_overview(self):
with self.doc.create(Section('Overview')):
self.doc.append(Command('centering'))
with self.overview_table as table:
table.add_hline()
table.add_row(bold("Index"), bold("File Name"), bold("Result"))
table.add_hline()
table.end_table_header()
The second function is as follows:
def add_data_to_report(self):
with self.overview_table as overview_table:
overview_table.add_hline()
Calling the second function crashes the program. I've tried searching for similar errors, but the closest I could get was that __enter__ was not defined. I'm not sure how to proceed from there.
The complete error message is
File "/Users/user/IdeaProjects/report/src/reportgen.py", line 46, in add_data_to_report
with self.overview_table as overview_table:
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/contextlib.py", line 133, in __enter__
del self.args, self.kwds, self.func
AttributeError: args
It'll be great help if someone can explain what went wrong. Thanks!
|
[
"It seems that the pylatex package has used the @contextlib.contextmanager decorator on the create method.\n @contextmanager\n def create(self, child):\n \"\"\"Add a LaTeX object to current container, context-manager style.\n Args\n ----\n child: `~.Container`\n An object to be added to the current container\n \"\"\"\n\n prev_data = self.data\n self.data = child.data # This way append works appends to the child\n\n yield child # allows with ... as to be used as well\n\n self.data = prev_data\n self.append(child)\n\nAs mentioned in the contextlib documentation,\n\nThe function being decorated must return a generator-iterator when called. This iterator must yield exactly one value, which will be bound to the targets in the with statement’s as clause, if any.\n\nThis means that you can use the returned value from the create function only once in a context as you have done.\nI would recommend you do one of\n\ndo everything you want to do with the overview_table inside a single context (that would be inside the initial set_up_overview function in your case)\ntake a look at the pylatex documentation and see if you can use the values they have set using self.append(child) in the create method\nadd the yielded object as an attribute on your class\n\n"
] |
[
1
] |
[] |
[] |
[
"pylatex",
"python",
"python_3.x"
] |
stackoverflow_0074582002_pylatex_python_python_3.x.txt
|
Q:
My code finds values in the list, but does not show any prompt when the value is not found
I was trying to do a binary search on the list CardData=[11,12,25,33,52,56,57,59,85,91]
this is my binary search method
def binsea(x,CardData):
front=0
back=len(CardData)
mid=len(CardData)//2
found=False
while front<back and found==False:
if x==CardData[mid]:
found=True
print(x,"is found at position",mid)
elif x<CardData[mid]:
back=mid
mid=(front+back)//2
elif x>CardData[mid]:
front=mid
mid=(front+back)//2
else:
print(x,"not found.")
it can find the the data in the list but does not do anything with this call.
binsea(55,CardData)
plzzzz help
def binsea(x,CardData):
front=0
back=len(CardData)
mid=len(CardData)//2
found=False
while front<back and found==False:
if x==CardData[mid]:
found=True
print(x,"is found at position",mid)
elif x<CardData[mid]:
back=mid
mid=(front+back)//2
elif x>CardData[mid]:
front=mid
mid=(front+back)//2
else:
print(x,"not found.")
binsea(55,CardData)
i was expecting a output of "55 not found."
A:
In general, I think the best way to debug your code yourself is often to add print statements. Try printing the values of front, back, and mid at the end of the loop (inside the loop). That should help you find your problem.
You could also look up the law of trichotomy.
A:
Your program is working. The condition elif x<CardData[mid]: will run as x = 55 and CardData[mid] = 56
Add some print statements it's easy to figure out
A:
This one should work (though I didn't test it thoroughly); that said, a dichotomy search would be better suited by writing a recursive function.
def binsea(x,CardData):
front=0
back=len(CardData)
mid=len(CardData)//2
found=False
while back - front > 1 and found==False:
print
if x==CardData[mid]:
found=True
print(x,"is found at position",mid)
elif x<CardData[mid]:
back=mid
mid=(front+back)//2
elif x>CardData[mid]:
front=mid
mid=(front+back)//2
else:
if not found:
print(x,"not found.")
Here's a working recursive approach (it returns the index of x in the original CardData list if found, else inf; you can then use the result in a print statement to get what you want):
from math import inf
CardData=[11,12,25,33,52,56,57,59,85,91]
def binsea(x,CardData):
if not CardData:
return inf
mid = len(CardData)//2
if x == CardData[mid]:
return mid
elif x < CardData[mid]:
return binsea(x,CardData[:mid])
else:
return mid + 1 + binsea(x,CardData[mid+1:])
def message(x, CardData):
index = binsea(x,CardData)
if index == inf:
print(f"{x} is not in {CardData}")
else:
print(f"{x} was found at index {index} in {CardData}")
message(33,CardData)
# 33 was found at index 3 in [11, 12, 25, 33, 52, 56, 57, 59, 85, 91]
message(55,CardData)
# 55 is not in [11, 12, 25, 33, 52, 56, 57, 59, 85, 91]
Of course, if the goal of all this is NOT to work on the dichotomy method,
Python allows a far simpler approach:
def is_in_list(x, CardData):
try:
print(f"{x} was found at index {CardData.index(x)} in {CardData}")
except:
print(f"{x} is not in {CardData}")
|
My code finds values in the list, but does not show any prompt when the value is not found
|
I was trying to do a binary search on the list CardData=[11,12,25,33,52,56,57,59,85,91]
this is my binary search method
def binsea(x,CardData):
front=0
back=len(CardData)
mid=len(CardData)//2
found=False
while front<back and found==False:
if x==CardData[mid]:
found=True
print(x,"is found at position",mid)
elif x<CardData[mid]:
back=mid
mid=(front+back)//2
elif x>CardData[mid]:
front=mid
mid=(front+back)//2
else:
print(x,"not found.")
it can find the the data in the list but does not do anything with this call.
binsea(55,CardData)
plzzzz help
def binsea(x,CardData):
front=0
back=len(CardData)
mid=len(CardData)//2
found=False
while front<back and found==False:
if x==CardData[mid]:
found=True
print(x,"is found at position",mid)
elif x<CardData[mid]:
back=mid
mid=(front+back)//2
elif x>CardData[mid]:
front=mid
mid=(front+back)//2
else:
print(x,"not found.")
binsea(55,CardData)
i was expecting a output of "55 not found."
|
[
"In general, I think the best way to debug your code yourself is often to add print statements. Try printing the values of front, back, and mid at the end of the loop (inside the loop). That should help you find your problem.\nYou could also look up the law of trichotomy.\n",
"Your program is working. The condition elif x<CardData[mid]: will run as x = 55 and CardData[mid] = 56\nAdd some print statements it's easy to figure out\n",
"This one should work (though I didn't test it thoroughly); that said, a dichotomy search would be better suited by writing a recursive function.\ndef binsea(x,CardData):\n front=0\n back=len(CardData)\n mid=len(CardData)//2\n found=False\n while back - front > 1 and found==False:\n print \n if x==CardData[mid]:\n found=True\n print(x,\"is found at position\",mid)\n elif x<CardData[mid]:\n back=mid\n mid=(front+back)//2\n elif x>CardData[mid]:\n front=mid\n mid=(front+back)//2\n else:\n if not found:\n print(x,\"not found.\")\n\nHere's a working recursive approach (it returns the index of x in the original CardData list if found, else inf; you can then use the result in a print statement to get what you want):\nfrom math import inf\n\nCardData=[11,12,25,33,52,56,57,59,85,91]\n\n\ndef binsea(x,CardData):\n if not CardData:\n return inf\n mid = len(CardData)//2\n if x == CardData[mid]:\n return mid\n elif x < CardData[mid]:\n return binsea(x,CardData[:mid])\n else:\n return mid + 1 + binsea(x,CardData[mid+1:])\n \n\ndef message(x, CardData):\n index = binsea(x,CardData)\n if index == inf:\n print(f\"{x} is not in {CardData}\")\n else:\n print(f\"{x} was found at index {index} in {CardData}\")\n \nmessage(33,CardData)\n# 33 was found at index 3 in [11, 12, 25, 33, 52, 56, 57, 59, 85, 91]\n\nmessage(55,CardData)\n# 55 is not in [11, 12, 25, 33, 52, 56, 57, 59, 85, 91] \n\nOf course, if the goal of all this is NOT to work on the dichotomy method,\nPython allows a far simpler approach:\ndef is_in_list(x, CardData):\n try:\n print(f\"{x} was found at index {CardData.index(x)} in {CardData}\")\n except:\n print(f\"{x} is not in {CardData}\")\n\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074582043_python.txt
|
Q:
Update user profile with user uuid
I want to update user profile passing user uuid as kwarg.
Here is the url:
path("profile/update/<uuid:pk>", UpdateProfile.as_view(), name="update_profile"),
However, after I try to update my profile, it gives me an error.
Here is my view:
class UpdateProfile(LoginRequiredMixin, UpdateView):
model = Profile
user_type_fields = {
"Buyer": ["photo", "first_name", "last_name", "city"],
"Celler": ["photo", "name", "city", "address"],
}
def get(self, request, *args, **kwargs):
print(kwargs)
self.fields = self.user_type_fields[get_user_model().objects.get(pk=kwargs["pk"]).type]
return super().get(request, *args, **kwargs)
And here is the error itself:
Page not found (404)
No profile found matching the query
As I understand, django tries to find profile with uuid as in url, doesn't find it and returns me this error. However, if I change model in my view to user, it wouldn't be able to find fields as they belong to profile model. The only working option was to pass profile id as kwarg, but I don`t find it preferrable due to security reasons.
Could someone give me an advice on how to update profile with user uuid in kwargs?
Thanks in advance!
UPD:
Here are User and Profile models:
class CustomUser(AbstractBaseUser, PermissionsMixin):
class UserTypeChoices(models.TextChoices):
SINGLE_VOLUNTEER = "Single Volunteer", _("Single Volunteer")
VOLUNTEERS_ORGANISATION = "Volunteers Organisation", _("Volunteers Organisation")
CIVIL_PERSON = "Civil Person", _("Civil Person")
MILITARY_PERSON = "Military Person", _("Military Person")
type = models.CharField(
max_length=23,
choices=UserTypeChoices.choices,
)
uuid = models.UUIDField(
primary_key=True,
default=uuid4,
unique=True,
db_index=True,
editable=False,
)
email = models.EmailField(
_("email address"),
null=True,
blank=True,
)
phone = PhoneNumberField(
_("phone"),
null=True,
blank=True,
)
is_staff = models.BooleanField(
_("staff status"),
default=False,
help_text=_("Designates whether the user can log into this admin site."),
)
is_active = models.BooleanField(
_("active"),
default=True,
help_text=_(
"Designates whether this user should be treated as active. " "Unselect this instead of deleting accounts."
),
)
def __str__(self):
if self.email:
return str(self.email)
else:
return str(self.phone)
USERNAME_FIELD = "email"
objects = CustomUserManager()
class Profile(models.Model):
user = models.OneToOneField(to="accounts.CustomUser", on_delete=models.CASCADE, blank=True, null=True)
photo = models.ImageField(upload_to="profile/", blank=True, null=True, default="profile/profile_default.png")
name = models.CharField(_("name"), max_length=150, blank=True, null=True, default=None)
first_name = models.CharField(_("first name"), max_length=150, blank=True, null=True, default=None)
last_name = models.CharField(_("last name"), max_length=150, blank=True, null=True, default=None)
city = models.CharField(_("city"), max_length=150, blank=True, null=True, default=None)
address = PlainLocationField()
def __str__(self):
if self.user.email:
return str(self.user.email)
else:
return str(self.user.phone)
A:
Assuming the following model, where a user only has one profile:
class Profile(models.Model):
user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
photo = models.ImageField()
# ... your other fields
You can then overwrite the get_object() method:
class UpdateProfile(LoginRequiredMixin, UpdateView):
model = Profile
fields = ['photo', '...']
def get_object(self):
user = get_user_model().objects.get(pk=self.kwargs['pk'])
profile = user.profile
return profile
And then use the UpdateView as normal.
|
Update user profile with user uuid
|
I want to update user profile passing user uuid as kwarg.
Here is the url:
path("profile/update/<uuid:pk>", UpdateProfile.as_view(), name="update_profile"),
However, after I try to update my profile, it gives me an error.
Here is my view:
class UpdateProfile(LoginRequiredMixin, UpdateView):
model = Profile
user_type_fields = {
"Buyer": ["photo", "first_name", "last_name", "city"],
"Celler": ["photo", "name", "city", "address"],
}
def get(self, request, *args, **kwargs):
print(kwargs)
self.fields = self.user_type_fields[get_user_model().objects.get(pk=kwargs["pk"]).type]
return super().get(request, *args, **kwargs)
And here is the error itself:
Page not found (404)
No profile found matching the query
As I understand, django tries to find profile with uuid as in url, doesn't find it and returns me this error. However, if I change model in my view to user, it wouldn't be able to find fields as they belong to profile model. The only working option was to pass profile id as kwarg, but I don`t find it preferrable due to security reasons.
Could someone give me an advice on how to update profile with user uuid in kwargs?
Thanks in advance!
UPD:
Here are User and Profile models:
class CustomUser(AbstractBaseUser, PermissionsMixin):
class UserTypeChoices(models.TextChoices):
SINGLE_VOLUNTEER = "Single Volunteer", _("Single Volunteer")
VOLUNTEERS_ORGANISATION = "Volunteers Organisation", _("Volunteers Organisation")
CIVIL_PERSON = "Civil Person", _("Civil Person")
MILITARY_PERSON = "Military Person", _("Military Person")
type = models.CharField(
max_length=23,
choices=UserTypeChoices.choices,
)
uuid = models.UUIDField(
primary_key=True,
default=uuid4,
unique=True,
db_index=True,
editable=False,
)
email = models.EmailField(
_("email address"),
null=True,
blank=True,
)
phone = PhoneNumberField(
_("phone"),
null=True,
blank=True,
)
is_staff = models.BooleanField(
_("staff status"),
default=False,
help_text=_("Designates whether the user can log into this admin site."),
)
is_active = models.BooleanField(
_("active"),
default=True,
help_text=_(
"Designates whether this user should be treated as active. " "Unselect this instead of deleting accounts."
),
)
def __str__(self):
if self.email:
return str(self.email)
else:
return str(self.phone)
USERNAME_FIELD = "email"
objects = CustomUserManager()
class Profile(models.Model):
user = models.OneToOneField(to="accounts.CustomUser", on_delete=models.CASCADE, blank=True, null=True)
photo = models.ImageField(upload_to="profile/", blank=True, null=True, default="profile/profile_default.png")
name = models.CharField(_("name"), max_length=150, blank=True, null=True, default=None)
first_name = models.CharField(_("first name"), max_length=150, blank=True, null=True, default=None)
last_name = models.CharField(_("last name"), max_length=150, blank=True, null=True, default=None)
city = models.CharField(_("city"), max_length=150, blank=True, null=True, default=None)
address = PlainLocationField()
def __str__(self):
if self.user.email:
return str(self.user.email)
else:
return str(self.user.phone)
|
[
"Assuming the following model, where a user only has one profile:\n class Profile(models.Model):\n user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)\n photo = models.ImageField()\n # ... your other fields\n\nYou can then overwrite the get_object() method:\n class UpdateProfile(LoginRequiredMixin, UpdateView):\n model = Profile\n fields = ['photo', '...']\n\n def get_object(self):\n user = get_user_model().objects.get(pk=self.kwargs['pk'])\n profile = user.profile\n return profile\n\n\nAnd then use the UpdateView as normal.\n"
] |
[
1
] |
[] |
[] |
[
"django",
"django_views",
"error_handling",
"python"
] |
stackoverflow_0074581549_django_django_views_error_handling_python.txt
|
Q:
Pandas dataframe with two columns but only shows one in shape function
The original dataframe has a column called release_year and a column called rating, and each year might include several ratings. I tried to calculate the average rating of each year and return a two column dataframe.
df = df.groupby('release_year')['rating'].mean()
new_df = pd.DataFrame(df)
The result looks like a two column datafrme, but when I use shape funtion, it shows there's one only.
new_df.shape
>>>(86, 1)
The dataframe I get
rating
release_year
1921 8.200000
1924 8.100000
1925 8.100000
1926 8.100000
1927 8.200000
... ...
2018 8.300000
2019 8.233333
2020 8.200000
2021 8.100000
2022 8.150000
A:
when you do the groupby , the grouped column becomes INDEX.
example:
df:
INDEX
COL1
COL2
0
ITEM1
ITEM2
df.groupby('col1'):
COL1(NOW INDEX)
COL2
ITEM1
ITEM2
you can use df.reset_index() to get indexes and change it to a column.
|
Pandas dataframe with two columns but only shows one in shape function
|
The original dataframe has a column called release_year and a column called rating, and each year might include several ratings. I tried to calculate the average rating of each year and return a two column dataframe.
df = df.groupby('release_year')['rating'].mean()
new_df = pd.DataFrame(df)
The result looks like a two column datafrme, but when I use shape funtion, it shows there's one only.
new_df.shape
>>>(86, 1)
The dataframe I get
rating
release_year
1921 8.200000
1924 8.100000
1925 8.100000
1926 8.100000
1927 8.200000
... ...
2018 8.300000
2019 8.233333
2020 8.200000
2021 8.100000
2022 8.150000
|
[
"when you do the groupby , the grouped column becomes INDEX.\nexample:\ndf:\n\n\n\n\nINDEX\nCOL1\nCOL2\n\n\n\n\n0\nITEM1\nITEM2\n\n\n\n\ndf.groupby('col1'):\n\n\n\n\nCOL1(NOW INDEX)\nCOL2\n\n\n\n\nITEM1\nITEM2\n\n\n\n\nyou can use df.reset_index() to get indexes and change it to a column.\n"
] |
[
1
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074582248_dataframe_pandas_python.txt
|
Q:
find numbers in string in selenium
In Python and Selenium, how do I find numeric characters in a text and put them in a variable?
for example :
text = Your verification code is: 5674
I need to find the number 5674 from the text and put it in a variable.
Result »» x = 5674
import re
txt = "Your verification code is: 5674"
x = is_digit(txt)
print(x)
x »»» 5674
A:
If the message is always formatted like this you can do:
text[text.find(":"):].strip() # -> 5764
or
text.strip("Your verification code is:") # -> 5764
A:
Well if you really expect just a single verification integer at the end, you could use re.search():
text = "Your verification code is: 5674";
code = re.search(r'\d+$', text).group()
print(code) # 5674
|
find numbers in string in selenium
|
In Python and Selenium, how do I find numeric characters in a text and put them in a variable?
for example :
text = Your verification code is: 5674
I need to find the number 5674 from the text and put it in a variable.
Result »» x = 5674
import re
txt = "Your verification code is: 5674"
x = is_digit(txt)
print(x)
x »»» 5674
|
[
"If the message is always formatted like this you can do:\ntext[text.find(\":\"):].strip() # -> 5764\n\nor\ntext.strip(\"Your verification code is:\") # -> 5764\n\n",
"Well if you really expect just a single verification integer at the end, you could use re.search():\ntext = \"Your verification code is: 5674\";\ncode = re.search(r'\\d+$', text).group()\nprint(code) # 5674\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"python",
"selenium"
] |
stackoverflow_0074582238_python_selenium.txt
|
Q:
How to extract text with strikethroughs from PDF files using Python
I'm currently trying to extract information from lots of PDF forms such as this:
The text 'female' should be extracted here. So contrary to my title, I'm actually trying to extract text with no strikethroughs rather than text that with strikethroughs. But if I can identify which words with strikethroughs, I can easily identify the inverse.
Gaining inspiration from this post, I came up with this set of codes:
import os
import glob
from pdf2docx import parse
from docx import Document
lst = []
files = glob.glob(os.getcwd() + r'\PDFs\*.pdf')
for i in range(len(files)):
filename = files[i].split('\\')[-1].split('.')[-2]
parse(files[i])
document = Document(os.getcwd() + rf'\PDFs\{filename}.docx')
for p in document.paragraphs:
for run in p.runs:
if run.font.strike:
lst.append(run.text)
os.remove(os.getcwd() + rf'\PDFs\{filename}.docx')
What the above code does is to convert all my PDF files into word documents (docx), and then search through the word documents for text with strikethroughs, extract those text, then delete the word document.
As you may have rightfully suspected, this set of code is very slow and inefficient, taking about 30s to run on my sample set of 4 PDFs with less than 10 pages combined.
I don't believe this is the best way to do this. However, when I did some research online, pdf2docx extracts data from PDFs using PyMuPDF, but yet PyMuPDF do not come with the capability to recognise strikethroughs in PDF text. How could this be so? When pdf2docx could perfectly convert strikethroughs in PDFs into docx document, indicating that the strikethroughs are being recognised at some level.
All in all, I would like to seek advice on whether or not it is possible to extract text with strikethroughs in PDF using Python. Thank you!
A:
Disclaimer: I am the author of borb, the library suggested in this answer
Ultimately, the exact code will end up varying depending on how strikethrough is implemented in your PDF. Allow me to clarify:
A PDF document (typically) has no notion of structure. So while we may see a paragraph of text, made up of several lines of text, a PDF (for the most part) just contains rendering instructions.
Things like:
Go to X, Y
Set the current font to Helvetica-Bold
Set the current color to black
Draw the letter "H"
Go to X, Y (moving slightly to the right this time)
Draw the letter "e"
etc
So in all likelihood, the text that is striked through is not marked as such in any meaningful way.
I think there are 2 options:
PDF has the concept of annotations. These are typically pieces of content that are added on top of a page. These can be extra text, geometric figures, etc. There is a specific annotation for strikethrough.
It might be an annotation, but a geometric figure (in this case a line) that simply appears over the text.
It might be a drawing instruction (inside the page content stream that is) that simply renders a black line over the text.
Your PDF might contain one (or more) of these, depending on which software initially created the strikethrough.
You can identify all of these using borb.
What I would do (in pseudo-code):
Extend SimpleTextExtraction (this is the main class in borb that deals with extracting text from a PDF)
Whenever this class sees an event (this is typically the parser having finished a particular instruction) you can check whether you saw a text-rendering instruction, or a line-drawing instruction. Keep track of text, and keep track of lines (in particular their bounding boxes).
When you have finished processing all events on a page, get all the annotations from the page, and filter out strikethrough annotations. Keep track of their bounding boxes.
From the list of TextRenderEvent objects, filter out those whose bounding box overlaps with: either a line, or a strikethrough bounding box
Copy the base algorithm for rebuilding text from these events
A:
If these strikethroughs in fact are annotations, PyMuPDF offers a simple and extremely fast solution:
On a page make a list of all strikethrough annotation rectangles and extract the text "underneath" them.
Or, similarly, look at keywords you are interested in (like "male", "female") and look if any is covered by a strikethrough annot.
# strike out annotation rectangles
st_rects = [a.rect for a in page.annots(types=[fitz.PDF_ANNOT_STRIKE_OUT])]
words = page.get_text("words") # the words on the page
for rect in st_rects:
for w in words:
wrect = fitz.Rect(w[:4]) # rect of the word
wtext = w[4] # word text
if wrect.intersects(rect):
print(f"{wtext} is strike out")
# the above checks if a word area intersects a strike out rect
# B/O mostly sloppy strike out rectangle definitions the safest way.
# alternatively, simpler:
for rect in st_rects:
print(page.get_textbox(rect + (-5, -5, 5, 5)), "is striked out")
# here I have increased the strike out rect by 5 points in every direction
# in the hope to cover the respective text.
Another case are PDF drawings, so-called "line art". These are no annotations (which can be removed) but things like lines, curves, rectangles - permanently stored in the page's rendering code objects (/Contents).
PyMuPDF also lets you extract this line art. If your text is striked-out with this method, then there exist overlaps between text rectangles and line art rectangles.
Office software (MS Word, LibreOffice) usually uses thin rectangles instead of true lines to better cope with zoomed displays -- so to catch all those cases, you must select both, horizontal lines and rectangles with small absolute heights where the width is also much larger.
Here is code that extracts those horizontal lines and "pseudo-lines" and a page:
lines = [] # to be filled with horizontal "lines": thin rectangles
paths = page.get_drawings() # list of drawing dictionary objects
for path in paths: # dictionary with single draw commands
for item in path["items"]: # check item types
if item[0] in ("c", "qu"): # skip curves and quads
continue
if item[0] == "l": # a true line
p1, p2 = item[1:] # start / stop points
if p1.y != p2.y: # skip non-horizontal lines
continue
# make a thin rectangle of height 2
rect = fitz.Rect(p1.x, p1.y - 1, p2.x, p2.y + 1)
lines.append(rect)
elif item[0] == "re": # a rectangle, check if roughly a horizontal line
rect = item[1] # the item's rectangle
if rect.width <= 2 * rect.height or rect.height > 4:
continue # not a pseudo-line
lines.append(rect)
Now you can use these line rectangles to check any intersections with text rectangles.
|
How to extract text with strikethroughs from PDF files using Python
|
I'm currently trying to extract information from lots of PDF forms such as this:
The text 'female' should be extracted here. So contrary to my title, I'm actually trying to extract text with no strikethroughs rather than text that with strikethroughs. But if I can identify which words with strikethroughs, I can easily identify the inverse.
Gaining inspiration from this post, I came up with this set of codes:
import os
import glob
from pdf2docx import parse
from docx import Document
lst = []
files = glob.glob(os.getcwd() + r'\PDFs\*.pdf')
for i in range(len(files)):
filename = files[i].split('\\')[-1].split('.')[-2]
parse(files[i])
document = Document(os.getcwd() + rf'\PDFs\{filename}.docx')
for p in document.paragraphs:
for run in p.runs:
if run.font.strike:
lst.append(run.text)
os.remove(os.getcwd() + rf'\PDFs\{filename}.docx')
What the above code does is to convert all my PDF files into word documents (docx), and then search through the word documents for text with strikethroughs, extract those text, then delete the word document.
As you may have rightfully suspected, this set of code is very slow and inefficient, taking about 30s to run on my sample set of 4 PDFs with less than 10 pages combined.
I don't believe this is the best way to do this. However, when I did some research online, pdf2docx extracts data from PDFs using PyMuPDF, but yet PyMuPDF do not come with the capability to recognise strikethroughs in PDF text. How could this be so? When pdf2docx could perfectly convert strikethroughs in PDFs into docx document, indicating that the strikethroughs are being recognised at some level.
All in all, I would like to seek advice on whether or not it is possible to extract text with strikethroughs in PDF using Python. Thank you!
|
[
"Disclaimer: I am the author of borb, the library suggested in this answer\nUltimately, the exact code will end up varying depending on how strikethrough is implemented in your PDF. Allow me to clarify:\nA PDF document (typically) has no notion of structure. So while we may see a paragraph of text, made up of several lines of text, a PDF (for the most part) just contains rendering instructions.\nThings like:\n\nGo to X, Y\nSet the current font to Helvetica-Bold\nSet the current color to black\nDraw the letter \"H\"\nGo to X, Y (moving slightly to the right this time)\nDraw the letter \"e\"\netc\n\nSo in all likelihood, the text that is striked through is not marked as such in any meaningful way.\nI think there are 2 options:\n\nPDF has the concept of annotations. These are typically pieces of content that are added on top of a page. These can be extra text, geometric figures, etc. There is a specific annotation for strikethrough.\nIt might be an annotation, but a geometric figure (in this case a line) that simply appears over the text.\nIt might be a drawing instruction (inside the page content stream that is) that simply renders a black line over the text.\n\nYour PDF might contain one (or more) of these, depending on which software initially created the strikethrough.\nYou can identify all of these using borb.\nWhat I would do (in pseudo-code):\n\nExtend SimpleTextExtraction (this is the main class in borb that deals with extracting text from a PDF)\nWhenever this class sees an event (this is typically the parser having finished a particular instruction) you can check whether you saw a text-rendering instruction, or a line-drawing instruction. Keep track of text, and keep track of lines (in particular their bounding boxes).\nWhen you have finished processing all events on a page, get all the annotations from the page, and filter out strikethrough annotations. Keep track of their bounding boxes.\nFrom the list of TextRenderEvent objects, filter out those whose bounding box overlaps with: either a line, or a strikethrough bounding box\nCopy the base algorithm for rebuilding text from these events\n\n",
"If these strikethroughs in fact are annotations, PyMuPDF offers a simple and extremely fast solution:\nOn a page make a list of all strikethrough annotation rectangles and extract the text \"underneath\" them.\nOr, similarly, look at keywords you are interested in (like \"male\", \"female\") and look if any is covered by a strikethrough annot.\n# strike out annotation rectangles\nst_rects = [a.rect for a in page.annots(types=[fitz.PDF_ANNOT_STRIKE_OUT])]\nwords = page.get_text(\"words\") # the words on the page\nfor rect in st_rects:\n for w in words:\n wrect = fitz.Rect(w[:4]) # rect of the word\n wtext = w[4] # word text\n if wrect.intersects(rect):\n print(f\"{wtext} is strike out\")\n\n# the above checks if a word area intersects a strike out rect\n# B/O mostly sloppy strike out rectangle definitions the safest way.\n# alternatively, simpler:\n\nfor rect in st_rects:\n print(page.get_textbox(rect + (-5, -5, 5, 5)), \"is striked out\")\n\n# here I have increased the strike out rect by 5 points in every direction\n# in the hope to cover the respective text.\n\nAnother case are PDF drawings, so-called \"line art\". These are no annotations (which can be removed) but things like lines, curves, rectangles - permanently stored in the page's rendering code objects (/Contents).\nPyMuPDF also lets you extract this line art. If your text is striked-out with this method, then there exist overlaps between text rectangles and line art rectangles.\nOffice software (MS Word, LibreOffice) usually uses thin rectangles instead of true lines to better cope with zoomed displays -- so to catch all those cases, you must select both, horizontal lines and rectangles with small absolute heights where the width is also much larger.\nHere is code that extracts those horizontal lines and \"pseudo-lines\" and a page:\nlines = [] # to be filled with horizontal \"lines\": thin rectangles\npaths = page.get_drawings() # list of drawing dictionary objects\nfor path in paths: # dictionary with single draw commands\n for item in path[\"items\"]: # check item types\n if item[0] in (\"c\", \"qu\"): # skip curves and quads\n continue\n if item[0] == \"l\": # a true line\n p1, p2 = item[1:] # start / stop points\n if p1.y != p2.y: # skip non-horizontal lines\n continue\n # make a thin rectangle of height 2\n rect = fitz.Rect(p1.x, p1.y - 1, p2.x, p2.y + 1)\n lines.append(rect)\n elif item[0] == \"re\": # a rectangle, check if roughly a horizontal line\n rect = item[1] # the item's rectangle\n if rect.width <= 2 * rect.height or rect.height > 4:\n continue # not a pseudo-line\n lines.append(rect)\n\nNow you can use these line rectangles to check any intersections with text rectangles.\n"
] |
[
1,
1
] |
[] |
[] |
[
"pdf",
"python"
] |
stackoverflow_0074533481_pdf_python.txt
|
Q:
Selecting rows in 2-D numpy array based on subset of column values
Suppose I have the following numpy array:
a = np.array([[1, 1, 0, 0, 1],
[1, 1, 0, 0, 0],
[1, 0, 0, 1, 1],
[1, 1, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 1, 0, 0, 0],
[0, 0, 0, 1, 0],
[1, 1, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 1, 1, 0, 1],
[1, 1, 0, 0, 0],
[1, 1, 0, 0, 1],
[1, 1, 0, 0, 0],
[1, 0, 0, 1, 0],
[1, 0, 1, 1, 0]])
I want to select only the rows, where column with index 1 have value 1 and column with index 2 have value 0.
i tried the following:
evidence = {1:1,2:0}
mask = a[:,list(evidence.keys())] == list(evidence.values())
But after that i am stuck.
how can I do it in numpy 2-D array?
A:
Try:
out = a[(a[:, 1] == 1) & (a[:, 2] == 0)]
Given a dictionary of column, value pairs, you could use:
evidence = {1:1,2:0}
out = a[ np.logical_and.reduce([a[:, c] == v for c, v in evidence.items()]) ]
which generalizes the above solution to a sequence of &.
|
Selecting rows in 2-D numpy array based on subset of column values
|
Suppose I have the following numpy array:
a = np.array([[1, 1, 0, 0, 1],
[1, 1, 0, 0, 0],
[1, 0, 0, 1, 1],
[1, 1, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 1, 0, 0, 0],
[0, 0, 0, 1, 0],
[1, 1, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 1, 1, 0, 1],
[1, 1, 0, 0, 0],
[1, 1, 0, 0, 1],
[1, 1, 0, 0, 0],
[1, 0, 0, 1, 0],
[1, 0, 1, 1, 0]])
I want to select only the rows, where column with index 1 have value 1 and column with index 2 have value 0.
i tried the following:
evidence = {1:1,2:0}
mask = a[:,list(evidence.keys())] == list(evidence.values())
But after that i am stuck.
how can I do it in numpy 2-D array?
|
[
"Try:\nout = a[(a[:, 1] == 1) & (a[:, 2] == 0)]\n\nGiven a dictionary of column, value pairs, you could use:\nevidence = {1:1,2:0}\nout = a[ np.logical_and.reduce([a[:, c] == v for c, v in evidence.items()]) ]\n\nwhich generalizes the above solution to a sequence of &.\n"
] |
[
1
] |
[] |
[] |
[
"numpy",
"python"
] |
stackoverflow_0074582332_numpy_python.txt
|
Q:
How can i test a void function in python using pytest?
I just started unit testing in python using pytest. Well, when I have a function with a return value, with the "assert" I can compare a certain value with the value that the function return.
But if I had a void function that returns nothing and does a print at the end, for example:
def function() -> None:
number = randint(0, 4)
if (number == 0):
print("Number 0")
elif (number == 1):
print("Number 1")
elif (number == 2):
print("Number 2")
elif (number == 3):
print("Number 3")
elif (number == 4):
print("Number 4")
How can i test this simple function to get 100% code coverage?
One method I've found to test this function is to do a return of the value (instead of print) and print it later, and then use the assert. But I wanted to know if it was possible to avoid this and do a test directly on the print statemant.
A:
You can redirect sys.stdout (the stream that print writes to) to a buffer and then examine or assert the contents of the buffer.
>>> import io
>>> import contextlib
>>>
>>> def f():print('X')
...
>>> buf = io.StringIO()
>>> with contextlib.redirect_stdout(buf):
... f()
...
>>> print(repr(buf.getvalue()))
'X\n'
>>>
>>> buf.close()
(Recall that print() appends the value of its end argument to the line, which defaults to '\n').
A:
I suggest having a look at the plugin pytest-mock. It allows you to mock collaborating objects of your code under test.
Consider the following code under test:
# production.py
def say_hello() -> None:
print('Hello World.')
you can easily mock this now with
# production_test.py
from production import say_hello
def test_greeting(mocker):
# The "mocker" fixture is auto-magicall inserted by pytest,
# once the extenson 'pytest-mock' is installed
printer = mocker.patch('builtins.print')
say_hello()
assert printer.call_count == 1
You can also assert the arguments the printer function was called with, etc. You will find a lot of details in their useful documentation.
Now, consider you do not want to access the printer, but have a code with some undesirable side-effects (e.g. an operation takes forever, or the result is non-predictable (random).) Let's have another example, say
# deep_though.py
class DeepThought:
#: Seven and a half million years in seconds
SEVEN_HALF_MIO_YEARS = 2.366771e14
@staticmethod
def compute_answer() -> int:
time.sleep(DeepThought.SEVEN_HALF_MIO_YEARS)
return 42
yeah, I personally don't want my test suite to run 7.5 mio years. So, what do we do?
# deep_thought_test.py
from deep_thought import DeepThought
def test_define_return_value(mocker) -> None:
# We use the internal python lookup path to the method
# as an identifier (from the location it is called)
mocker.patch('deep_thought.DeepThought.compute_answer', return_value=12)
assert DeepThought.compute_answer() == 12
Two more minor remarks, not directly related to the post:
A high code coverage (80% - 90%) is a good goal. I personally try to stck around 90-95%. However, 100% coverage is usually not necessary. Simple(!) data items and log-statements can usually be ignored.
It's a good practice to use a logger, instead of print. See Question 6918493 for example.
|
How can i test a void function in python using pytest?
|
I just started unit testing in python using pytest. Well, when I have a function with a return value, with the "assert" I can compare a certain value with the value that the function return.
But if I had a void function that returns nothing and does a print at the end, for example:
def function() -> None:
number = randint(0, 4)
if (number == 0):
print("Number 0")
elif (number == 1):
print("Number 1")
elif (number == 2):
print("Number 2")
elif (number == 3):
print("Number 3")
elif (number == 4):
print("Number 4")
How can i test this simple function to get 100% code coverage?
One method I've found to test this function is to do a return of the value (instead of print) and print it later, and then use the assert. But I wanted to know if it was possible to avoid this and do a test directly on the print statemant.
|
[
"You can redirect sys.stdout (the stream that print writes to) to a buffer and then examine or assert the contents of the buffer.\n>>> import io\n>>> import contextlib\n>>> \n>>> def f():print('X')\n... \n>>> buf = io.StringIO()\n>>> with contextlib.redirect_stdout(buf):\n... f()\n... \n>>> print(repr(buf.getvalue()))\n'X\\n'\n>>> \n>>> buf.close()\n\n(Recall that print() appends the value of its end argument to the line, which defaults to '\\n').\n",
"I suggest having a look at the plugin pytest-mock. It allows you to mock collaborating objects of your code under test.\nConsider the following code under test:\n# production.py \n\ndef say_hello() -> None:\n print('Hello World.')\n\nyou can easily mock this now with\n# production_test.py\nfrom production import say_hello\n\ndef test_greeting(mocker):\n # The \"mocker\" fixture is auto-magicall inserted by pytest, \n # once the extenson 'pytest-mock' is installed\n printer = mocker.patch('builtins.print')\n say_hello()\n assert printer.call_count == 1\n\nYou can also assert the arguments the printer function was called with, etc. You will find a lot of details in their useful documentation.\n\nNow, consider you do not want to access the printer, but have a code with some undesirable side-effects (e.g. an operation takes forever, or the result is non-predictable (random).) Let's have another example, say\n# deep_though.py\n\nclass DeepThought:\n #: Seven and a half million years in seconds\n SEVEN_HALF_MIO_YEARS = 2.366771e14\n\n @staticmethod\n def compute_answer() -> int:\n time.sleep(DeepThought.SEVEN_HALF_MIO_YEARS)\n return 42\n\nyeah, I personally don't want my test suite to run 7.5 mio years. So, what do we do?\n# deep_thought_test.py \nfrom deep_thought import DeepThought\n\ndef test_define_return_value(mocker) -> None:\n # We use the internal python lookup path to the method \n # as an identifier (from the location it is called) \n mocker.patch('deep_thought.DeepThought.compute_answer', return_value=12)\n assert DeepThought.compute_answer() == 12\n\n\nTwo more minor remarks, not directly related to the post:\n\nA high code coverage (80% - 90%) is a good goal. I personally try to stck around 90-95%. However, 100% coverage is usually not necessary. Simple(!) data items and log-statements can usually be ignored.\nIt's a good practice to use a logger, instead of print. See Question 6918493 for example.\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"pytest",
"python",
"unit_testing"
] |
stackoverflow_0074578124_pytest_python_unit_testing.txt
|
Q:
Is there a way to get get all mentions of a certain pattern and following values in a string in python
Im trying to get all values in a string that's looks like the following:
example = 'jnkfksieufsieufsejfuies Title="Something" daowijdaowdnobngfoinbijfgh Title="something else"
is there a way to get the values following the Title variable in the string.
I thought to use some sort method to get all Title mentions in the string, then be able to get the following values but im not sure how that is possible in python.
Im guessing i could use some pattern regognizion from the "re" dependency
A:
Use re.findall with a pattern having a group to match what's after the Title
example = 'jnkfksieufsieufsejfuies Title="Something" daowijdaowdnobngfoinbijfgh Title="something else"'
titles = re.findall(f'Title="([^"]+)"', example)
print(titles) # ['Something', 'something else']
|
Is there a way to get get all mentions of a certain pattern and following values in a string in python
|
Im trying to get all values in a string that's looks like the following:
example = 'jnkfksieufsieufsejfuies Title="Something" daowijdaowdnobngfoinbijfgh Title="something else"
is there a way to get the values following the Title variable in the string.
I thought to use some sort method to get all Title mentions in the string, then be able to get the following values but im not sure how that is possible in python.
Im guessing i could use some pattern regognizion from the "re" dependency
|
[
"Use re.findall with a pattern having a group to match what's after the Title\nexample = 'jnkfksieufsieufsejfuies Title=\"Something\" daowijdaowdnobngfoinbijfgh Title=\"something else\"'\ntitles = re.findall(f'Title=\"([^\"]+)\"', example)\nprint(titles) # ['Something', 'something else']\n\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074582283_python.txt
|
Q:
Why does my count is coming 1 instead calculating all the digits in the number in Python?
I am trying to calculate the number of digits in a random number, for example for number 5675, I am expecting a count value 4 as an output but instead of that , it's returning 1. I have tried to write the logic in a while loop until the condition satisfied.
Below is my code.
class Solution(object):
def calculate(self, num):
count_no = 0
while num > 0:
num = num / 10
count_no += 1
return count_no
if __name__ == "__main__":
p = Solution()
no = 5675
print(p.calculate(no))
A:
Your logic is right but You put return count_no in the while loop.
So it will returns in the first iteration, and will not continue till the end of your loop.
do this:
def calculate(self, num):
count_no = 0
while num > 0:
num = num // 10
count_no += 1
return count_no
take a look at this link to learn about blocks in python.
Thanks to @Aurora19, Please chnage / to // for integer division.
A:
There are multiple bugs in your code.
What Mehrdad Pedramfar said. You return in the first loop iteration, while you should only return once you exit the loop.
Have a look at the value of num in each iteration. If you add print(num) to your loop, you'll see something like
5675
567.5
56.75
5.675
.5675
Not what you expected, right? That's because you're using the true division operator (/) instead of the integer division operator (//)
What's the point of the class? If you don't need a class, don't use one. Also, calling a method calculate is just bad. Call it something like number_of_digits.
Since this is a school assignment, I leave putting it all together to you.
A:
The problem of your solution is the return inside the while loop, in this way the value of counto_no is returned at the first iteration which is always 1. You have also to use the integer divider instead of the normale one, the integer divider is this: //.
Another solution to your problem can be the following:
def countDigit(self,num:int) -> int:
return len(str(num))
|
Why does my count is coming 1 instead calculating all the digits in the number in Python?
|
I am trying to calculate the number of digits in a random number, for example for number 5675, I am expecting a count value 4 as an output but instead of that , it's returning 1. I have tried to write the logic in a while loop until the condition satisfied.
Below is my code.
class Solution(object):
def calculate(self, num):
count_no = 0
while num > 0:
num = num / 10
count_no += 1
return count_no
if __name__ == "__main__":
p = Solution()
no = 5675
print(p.calculate(no))
|
[
"Your logic is right but You put return count_no in the while loop.\nSo it will returns in the first iteration, and will not continue till the end of your loop.\ndo this:\ndef calculate(self, num):\n count_no = 0\n while num > 0:\n num = num // 10\n count_no += 1\n\n return count_no\n\ntake a look at this link to learn about blocks in python.\nThanks to @Aurora19, Please chnage / to // for integer division.\n",
"There are multiple bugs in your code.\n\nWhat Mehrdad Pedramfar said. You return in the first loop iteration, while you should only return once you exit the loop.\nHave a look at the value of num in each iteration. If you add print(num) to your loop, you'll see something like\n\n5675\n567.5\n56.75\n5.675\n.5675\n\nNot what you expected, right? That's because you're using the true division operator (/) instead of the integer division operator (//)\n\nWhat's the point of the class? If you don't need a class, don't use one. Also, calling a method calculate is just bad. Call it something like number_of_digits.\n\nSince this is a school assignment, I leave putting it all together to you.\n",
"The problem of your solution is the return inside the while loop, in this way the value of counto_no is returned at the first iteration which is always 1. You have also to use the integer divider instead of the normale one, the integer divider is this: //.\nAnother solution to your problem can be the following:\ndef countDigit(self,num:int) -> int:\n return len(str(num))\n\n"
] |
[
2,
1,
1
] |
[] |
[] |
[
"division",
"python",
"while_loop"
] |
stackoverflow_0074582097_division_python_while_loop.txt
|
Q:
How to alternate between multiple threads in Python?
I'm trying to alternate between 2 threads:
import threading
def test1():
for _ in range(3):
print("Test1")
def test2():
for _ in range(3):
print("Test2")
t1 = threading.Thread(target=test1)
t2 = threading.Thread(target=test2)
t1.start()
t2.start()
t1.join()
t2.join()
But, the result is as shown below:
Test1
Test1
Test1
Test2
Test2
Test2
I want the result as shown below:
Test1
Test2
Test1
Test2
Test1
Test2
Are there any ways to do that?
A:
You can get the alternate result with a global variable, lock and while statement as shown below:
import threading
owner = "Test1"
lock = threading.Lock()
def test1():
global owner
i = 0
while i < 3:
lock.acquire()
if owner == "Test1":
print("Test1")
owner = "Test2"
i += 1
lock.release()
def test2():
global owner
i = 0
while i < 3:
lock.acquire()
if owner == "Test2":
print("Test2")
owner = "Test1"
i += 1
lock.release()
t1 = threading.Thread(target=test1)
t2 = threading.Thread(target=test2)
t1.start()
t2.start()
t1.join()
t2.join()
Then, you can get the alternate result below:
Test1
Test2
Test1
Test2
Test1
Test2
You can also get the alternate result with a queue, lock and while statement as shown below:
import queue
import threading
lock = threading.Lock()
def test1(owner):
i = 0
while i < 3:
lock.acquire()
if owner.queue[0] == "Test1":
print("Test1")
owner.queue[0] = "Test2"
i += 1
lock.release()
def test2(owner):
i = 0
while i < 3:
lock.acquire()
if owner.queue[0] == "Test2":
print("Test2")
owner.queue[0] = "Test1"
i += 1
lock.release()
owner = queue.Queue()
owner.put("Test1")
t1 = threading.Thread(target=test1, args=(owner,))
t2 = threading.Thread(target=test2, args=(owner,))
t1.start()
t2.start()
t1.join()
t2.join()
Then, you can get the alternate result below:
Test1
Test2
Test1
Test2
Test1
Test2
|
How to alternate between multiple threads in Python?
|
I'm trying to alternate between 2 threads:
import threading
def test1():
for _ in range(3):
print("Test1")
def test2():
for _ in range(3):
print("Test2")
t1 = threading.Thread(target=test1)
t2 = threading.Thread(target=test2)
t1.start()
t2.start()
t1.join()
t2.join()
But, the result is as shown below:
Test1
Test1
Test1
Test2
Test2
Test2
I want the result as shown below:
Test1
Test2
Test1
Test2
Test1
Test2
Are there any ways to do that?
|
[
"You can get the alternate result with a global variable, lock and while statement as shown below:\nimport threading\nowner = \"Test1\"\nlock = threading.Lock()\n\ndef test1():\n global owner\n i = 0\n while i < 3:\n lock.acquire()\n if owner == \"Test1\":\n print(\"Test1\")\n owner = \"Test2\"\n i += 1\n lock.release()\n\ndef test2():\n global owner\n i = 0\n while i < 3:\n lock.acquire()\n if owner == \"Test2\":\n print(\"Test2\")\n owner = \"Test1\"\n i += 1\n lock.release()\n\nt1 = threading.Thread(target=test1)\nt2 = threading.Thread(target=test2)\n\nt1.start()\nt2.start()\n\nt1.join()\nt2.join()\n\nThen, you can get the alternate result below:\nTest1\nTest2\nTest1\nTest2\nTest1\nTest2\n\nYou can also get the alternate result with a queue, lock and while statement as shown below:\nimport queue\nimport threading\nlock = threading.Lock()\n\ndef test1(owner):\n i = 0\n while i < 3:\n lock.acquire()\n if owner.queue[0] == \"Test1\":\n print(\"Test1\")\n owner.queue[0] = \"Test2\"\n i += 1\n lock.release()\n\ndef test2(owner):\n i = 0\n while i < 3:\n lock.acquire()\n if owner.queue[0] == \"Test2\":\n print(\"Test2\")\n owner.queue[0] = \"Test1\"\n i += 1\n lock.release()\n \nowner = queue.Queue()\nowner.put(\"Test1\")\n\nt1 = threading.Thread(target=test1, args=(owner,))\nt2 = threading.Thread(target=test2, args=(owner,))\n\nt1.start()\nt2.start()\n\nt1.join()\nt2.join()\n\nThen, you can get the alternate result below:\nTest1\nTest2\nTest1\nTest2\nTest1\nTest2\n\n"
] |
[
0
] |
[
"I think your question here is about why the two functions are not executed simultaneously, but rather in sequence. The answer is that Python has a global interpreter lock (GIL). A single Python process will not (normally) run Python code in multiple parallel threads. There are exceptions to this, such as when running native code (in which case the GIL may be released).\nIn your trivial example there would be no need for threading of course. In a real world scenario the problem is actually less of a problem. Typically, CPU intensive tasks are offloaded to a native library (such as Pytorch, Numpy, Scipy, Pandas etc) all which are written in native code or has parallelization built in.\nIf you find yourself writing code that would be solved by utilizing multiple CPU cores to interpret Python code, there is most likely a better solution to your problem.\nThat said, have a look at the multiprocessing module, which can run multiple Python functions in parallel by utilizing multiple processes and parallel primitives (such as queues and map-reduce)\n"
] |
[
-2
] |
[
"alternate",
"multithreading",
"python",
"python_3.x",
"python_multithreading"
] |
stackoverflow_0074577448_alternate_multithreading_python_python_3.x_python_multithreading.txt
|
Q:
pygame window takes forever to start
So I'm following the alien invasion project from python crash course, at the beginning the book teaches how to open a simple window with a specific background color. I literally copy-pasted the code from the book and it still does not work.
import pygame
import sys
from settings import Settings
def run_game():
# Initialize game and create a screen object.
pygame.init()
# Init settings
my_settings = Settings()
screen = pygame.display.set_mode((my_settings.screen_widht, my_settings.screen_height))
pygame.display.set_caption("Alien Invasion")
# Start the main loop for the game.
while True:
# Watch for keyboard and mouse events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# Redraw the screen during each pass through the loop.
screen.fill(my_settings.bg_color)
# Make the most recently drawn screen visible.
pygame.display.flip()
run_game()
EDIT: To clarify, I'm not saying the code doesn't work, it works without errors but takes a minute to open... it's something with my system, but I don't know what it is, that's why I'm asking
Edit2: I realized that if I remove pygame.init() the window opens instantly, not sure what it means
A:
pygame.init() initializes all pygame modules. This may take some time on some systems. If you don't need all pygame modules, just leave it out. For the display and event handling it is not necessary to call pygame.init() at all. If you need other modules, you can itialize them separately (e.g. pygame.font.init(), pygame.mixer.init()).
See pygame.init()
Initialize all imported pygame modules. No exceptions will be raised if a module fails, but the total number if successful and failed inits will be returned as a tuple. You can always initialize individual modules manually, but pygame.init()initialize all imported pygame modules is a convenient way to get everything started. The init() functions for individual modules will raise exceptions when they fail.
You may want to initialize the different modules separately to speed up your program or to not use modules your game does not require.
|
pygame window takes forever to start
|
So I'm following the alien invasion project from python crash course, at the beginning the book teaches how to open a simple window with a specific background color. I literally copy-pasted the code from the book and it still does not work.
import pygame
import sys
from settings import Settings
def run_game():
# Initialize game and create a screen object.
pygame.init()
# Init settings
my_settings = Settings()
screen = pygame.display.set_mode((my_settings.screen_widht, my_settings.screen_height))
pygame.display.set_caption("Alien Invasion")
# Start the main loop for the game.
while True:
# Watch for keyboard and mouse events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# Redraw the screen during each pass through the loop.
screen.fill(my_settings.bg_color)
# Make the most recently drawn screen visible.
pygame.display.flip()
run_game()
EDIT: To clarify, I'm not saying the code doesn't work, it works without errors but takes a minute to open... it's something with my system, but I don't know what it is, that's why I'm asking
Edit2: I realized that if I remove pygame.init() the window opens instantly, not sure what it means
|
[
"pygame.init() initializes all pygame modules. This may take some time on some systems. If you don't need all pygame modules, just leave it out. For the display and event handling it is not necessary to call pygame.init() at all. If you need other modules, you can itialize them separately (e.g. pygame.font.init(), pygame.mixer.init()).\nSee pygame.init()\n\nInitialize all imported pygame modules. No exceptions will be raised if a module fails, but the total number if successful and failed inits will be returned as a tuple. You can always initialize individual modules manually, but pygame.init()initialize all imported pygame modules is a convenient way to get everything started. The init() functions for individual modules will raise exceptions when they fail.\nYou may want to initialize the different modules separately to speed up your program or to not use modules your game does not require.\n\n"
] |
[
0
] |
[] |
[] |
[
"pygame",
"python",
"python_3.x"
] |
stackoverflow_0074568087_pygame_python_python_3.x.txt
|
Q:
hand tracking system using opencv error:TypeError: handDetector.findHands() missing 1 required positional argument: 'img'
I'm following an online advanced CV course but the code wouldn't run properly for me.
These are the error messages I've gotten:
#Traceback (most recent call last):
#File "C:\Users\lihua\PycharmProjects\AdvancedComputerVision\HandTrackingModule.py", line 60,
#in <module>
#main ()
#File "C:\Users\lihua\PycharmProjects\AdvancedComputerVision\HandTrackingModule.py", line 48,
#in main
#img = detector.findHands(img)
#TypeError: handDetector.findHands() missing 1 required positional argument: 'img'
#[ WARN:0@2.697] global D:\a\opencv-python\opencv-
#python\opencv\modules\videoio\src\cap_msmf.cpp (539) `anonymous-
#namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
I don't understand what I did wrong as I followed the online tutorial exactly and it seems that it worked out fine with the person in the tutorial
import cv2
import mediapipe as mp
import time
class handDetector ():
#initialization
def __init__ (self,mode =False, maxHands =2, detectionCon=0.5,trackCon=0.5 ):
self.mode = mode
self.maxHands= maxHands
self.detectionCon =detectionCon
self.trackCon = trackCon
self.mpHands = mp.solutions.hands
self.hands = self.mpHands.Hands(self.mode,self.maxHands,
self.detectionCon,self.trackCon)
self.mpDraw = mp.solutions.drawing_utils
def findHands(self,img,draw =True):
imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
results = self.hands.process(imgRGB)
# print (results.multi_hand_landmarks)
if results.multi_hand_landmarks:
for handLms in results.multi_hand_landmarks:
if draw:
self.mpDraw.draw_landmarks(img, handLms, self.mpHands.HAND_CONNECTIONS)
return img
def main ():
pTime = 0
cTime = 0
cap = cv2.VideoCapture(0)
detector = handDetector
while True:
success, img = cap.read()
img = detector.findHands(img)
cTime = time.time()
fps = 1 / (cTime - pTime)
pTime = cTime
cv2.putText(img, str(int(fps)), (10, 70), cv2.FONT_HERSHEY_PLAIN, 3, (225, 0, 225), 3)
cv2.imshow('Image', img)
cv2.waitKey(1)
if __name__ == '__main__':
main ()
A:
You forgot to instantiate the class handDetector in the main function line 31, you have to add () otherwise you pass him the complete object without instantiating it.
A:
The error lies in the line
self.hands = self.mpHands.Hands(self.mode,self.maxHands,
self.detectionCon,self.trackCon)
The third argument is actually the model complexity instead of self.detection
try this:
self.complexity = 1
self.mpHands.Hands(self.mode,self.maxHands,self.complexity,
self.detectionCon,self.trackCon)
|
hand tracking system using opencv error:TypeError: handDetector.findHands() missing 1 required positional argument: 'img'
|
I'm following an online advanced CV course but the code wouldn't run properly for me.
These are the error messages I've gotten:
#Traceback (most recent call last):
#File "C:\Users\lihua\PycharmProjects\AdvancedComputerVision\HandTrackingModule.py", line 60,
#in <module>
#main ()
#File "C:\Users\lihua\PycharmProjects\AdvancedComputerVision\HandTrackingModule.py", line 48,
#in main
#img = detector.findHands(img)
#TypeError: handDetector.findHands() missing 1 required positional argument: 'img'
#[ WARN:0@2.697] global D:\a\opencv-python\opencv-
#python\opencv\modules\videoio\src\cap_msmf.cpp (539) `anonymous-
#namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
I don't understand what I did wrong as I followed the online tutorial exactly and it seems that it worked out fine with the person in the tutorial
import cv2
import mediapipe as mp
import time
class handDetector ():
#initialization
def __init__ (self,mode =False, maxHands =2, detectionCon=0.5,trackCon=0.5 ):
self.mode = mode
self.maxHands= maxHands
self.detectionCon =detectionCon
self.trackCon = trackCon
self.mpHands = mp.solutions.hands
self.hands = self.mpHands.Hands(self.mode,self.maxHands,
self.detectionCon,self.trackCon)
self.mpDraw = mp.solutions.drawing_utils
def findHands(self,img,draw =True):
imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
results = self.hands.process(imgRGB)
# print (results.multi_hand_landmarks)
if results.multi_hand_landmarks:
for handLms in results.multi_hand_landmarks:
if draw:
self.mpDraw.draw_landmarks(img, handLms, self.mpHands.HAND_CONNECTIONS)
return img
def main ():
pTime = 0
cTime = 0
cap = cv2.VideoCapture(0)
detector = handDetector
while True:
success, img = cap.read()
img = detector.findHands(img)
cTime = time.time()
fps = 1 / (cTime - pTime)
pTime = cTime
cv2.putText(img, str(int(fps)), (10, 70), cv2.FONT_HERSHEY_PLAIN, 3, (225, 0, 225), 3)
cv2.imshow('Image', img)
cv2.waitKey(1)
if __name__ == '__main__':
main ()
|
[
"You forgot to instantiate the class handDetector in the main function line 31, you have to add () otherwise you pass him the complete object without instantiating it.\n",
"The error lies in the line\nself.hands = self.mpHands.Hands(self.mode,self.maxHands,\n self.detectionCon,self.trackCon) \n\nThe third argument is actually the model complexity instead of self.detection\ntry this:\nself.complexity = 1\nself.mpHands.Hands(self.mode,self.maxHands,self.complexity,\n self.detectionCon,self.trackCon)\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"mediapipe",
"opencv",
"python"
] |
stackoverflow_0072234831_mediapipe_opencv_python.txt
|
Q:
How to Convert PDF file into CSV file using Python Pandas
I have a PDF file, I need to convert it into a CSV file this is my pdf file example as link https://online.flippingbook.com/view/352975479/ the code used is
import re
import parse
import pdfplumber
import pandas as pd
from collections import namedtuple
file = "Battery Voltage.pdf"
lines = []
total_check = 0
with pdfplumber.open(file) as pdf:
pages = pdf.pages
for page in pdf.pages:
text = page.extract_text()
for line in text.split('\n'):
print(line)
with the above script I am not getting proper output, For Time column "AM" is getting in the next line. The output I am getting is like this
A:
It may help you to see how the surface of a pdf is displayed to the screen. so that one string of plain text is placed part by part on the display. (Here I highlight where the first AM is to be placed.
As a side issue that first AM in the file is I think at first glance encoded as this block
BT
/F1 12 Tf
1 0 0 1 224.20265 754.6322 Tm
[<001D001E>] TJ
ET
Where in that area 1D = A and 1E = M
So If you wish to extract each LINE as it is displayed, by far the simplest way is to use a library such as pdftotext that especially outputs each row of text as seen on page.
Thus using an attack such as tabular comma separated you can expect each AM will be given its own row. Which should by logic be " ",AM," "," " but some extractors should say nan,AM,nan,nan
As text it looks like this from just one programmable line
pdftotext -layout "Battery Voltage.pdf"
That will output "Battery Voltage.txt" in the same work folder
Then placing that in a spreadsheet becomes
Now we can export in a couple of clicks (no longer) as "proper output" csv along with all its oddities that csv entails.
,,Battery Vo,ltage,
Sr No,DateT,Ime,Voltage (v),Ignition
1,01/11/2022,00:08:10,47.15,Off
,AM,,,
2,01/11/2022,00:23:10,47.15,Off
,AM,,,
3,01/11/2022,00:38:10,47.15,Off
,AM,,,
4,01/11/2022,00:58:10,47.15,Off
,AM,,,
5,01/11/2022,01:18:10,47.15,Off
,AM,,,
6,01/11/2022,01:33:10,47.15,Off
,AM,,,
7,01/11/2022,01:48:10,47.15,Off
,AM,,,
8,01/11/2022,02:03:10,47.15,Off
,AM,,,
9,01/11/2022,02:18:10,47.15,Off
,AM,,,
10,01/11/2022,02:37:12,47.15,Off
,AM,,,
So, if the edits were not done before csv generation it is simpler to post process in an editor, like this html page (no need for more apps)
,,Battery,Voltage,
Sr No,Date,Time,Voltage (v),Ignition
1,01/11/2022,00:08:10,47.15,Off,AM,,,
2,01/11/2022,00:23:10,47.15,Off,AM,,,
3,01/11/2022,00:38:10,47.15,Off,AM,,,
4,01/11/2022,00:58:10,47.15,Off,AM,,,
5,01/11/2022,01:18:10,47.15,Off,AM,,,
6,01/11/2022,01:33:10,47.15,Off,AM,,,
7,01/11/2022,01:48:10,47.15,Off,AM,,,
8,01/11/2022,02:03:10,47.15,Off,AM,,,
9,01/11/2022,02:18:10,47.15,Off,AM,,,
10,01/11/2022,02:37:12,47.15,Off,AM,,,
Then on re-import it looks more human generated
In discussions it was confirmed all that's desired is a means to a structured list and first parse using
pdftotext -layout -nopgbrk -x 0 -y 60 -W 800 -H 800 -fixed 6 "Battery Voltage.pdf" &type "battery voltage.txt"|findstr "O">battery.txt
will output regulated data columns for framing, with a fixed headline or splitting or otherwise using cleaned data.
1 01-11-2022 00:08:10 47.15 Off
2 01-11-2022 00:23:10 47.15 Off
3 01-11-2022 00:38:10 47.15 Off
4 01-11-2022 00:58:10 47.15 Off
5 01-11-2022 01:18:10 47.15 Off
...
32357 24-11-2022 17:48:43 45.40 On
32358 24-11-2022 17:48:52 44.51 On
32359 24-11-2022 17:48:55 44.51 On
32360 24-11-2022 17:48:58 44.51 On
32361 24-11-2022 17:48:58 44.51 On
At this stage we can use text handling such as csv or add json brackets
for /f "tokens=1,2,3,4,5 delims= " %%a In ('Findstr /C:"O" battery.txt') do echo csv is "%%a,%%b,%%c,%%d,%%e">output.txt
...
csv is "32357,24-11-2022,17:48:43,45.40,On"
csv is "32358,24-11-2022,17:48:52,44.51,On"
csv is "32359,24-11-2022,17:48:55,44.51,On"
csv is "32360,24-11-2022,17:48:58,44.51,On"
csv is "32361,24-11-2022,17:48:58,44.51,On"
So the request is for JSON (not my forte so you may need to improve on my code as I dont know what mongo expects)
here I drop a pdf onto a battery.bat
{"line_id":1,"created":{"date":"01-11-2022"},{"time":"00:08:10"},{"Voltage":"47.15"},{"State","Off"}}
{"line_id":2,"created":{"date":"01-11-2022"},{"time":"00:23:10"},{"Voltage":"47.15"},{"State","Off"}}
{"line_id":3,"created":{"date":"01-11-2022"},{"time":"00:38:10"},{"Voltage":"47.15"},{"State","Off"}}
{"line_id":4,"created":{"date":"01-11-2022"},{"time":"00:58:10"},{"Voltage":"47.15"},{"State","Off"}}
{"line_id":5,"created":{"date":"01-11-2022"},{"time":"01:18:10"},{"Voltage":"47.15"},{"State","Off"}}
{"line_id":6,"created":{"date":"01-11-2022"},{"time":"01:33:10"},{"Voltage":"47.15"},{"State","Off"}}
{"line_id":7,"created":{"date":"01-11-2022"},{"time":"01:48:10"},{"Voltage":"47.15"},{"State","Off"}}
{"line_id":8,"created":{"date":"01-11-2022"},{"time":"02:03:10"},{"Voltage":"47.15"},{"State","Off"}}
{"line_id":9,"created":{"date":"01-11-2022"},{"time":"02:18:10"},{"Voltage":"47.15"},{"State","Off"}}
{"line_id":10,"created":{"date":"01-11-2022"},{"time":"02:37:12"},{"Voltage":"47.15"},{"State","Off"}}
it is a bit slow as running in pure console so lets run it blinder by add @, it will still take time as we are working in plain text, so do expect a significant delay for 32,000+ lines = 2+1/2 minutes on my kit
pdftotext -layout -nopgbrk -x 0 -y 60 -W 700 -H 800 -fixed 8 "%~1" battery.txt
echo Heading however you wish it for json perhaps just opener [ but note only one redirect chevron >"%~dpn1.txt"
for /f "tokens=1,2,3,4,5 delims= " %%a In ('Findstr /C:"O" battery.txt') do @echo "%%a": { "Date": "%%b", "Time": "%%c", "Voltage": %%d, "Ignition": "%%e" },>>"%~dpn1.txt"
REM another json style could be { "Line_Id": %%a, "Date": "%%b", "Time": "%%c", "Voltage": %%d, "Ignition": "%%e" },
REM another for an array can simply be [%%a,"%%b","%%c",%%d,"%%e" ],
echo Tailing however you wish it for json perhaps just final closer ] but note double chevron >>"%~dpn1.txt"
To see progress change @echo { to @echo %%a&echo {
Thus, after a minute or so
however, it tends to add an extra minute for all that display activity! before the window closes as a sign of completion.
A:
For cases like these, build a parser that converts the unusable data into something you can use.
Logic below converts that exact file to a CSV, but will only work with that specific file contents.
Note that for this specific file you can ignore the AM/PM as the time is in 24h format.
import pdfplumber
file = "Battery Voltage.pdf"
skiplines = [
"Battery Voltage",
"AM",
"PM",
"Sr No DateTIme Voltage (v) Ignition",
""
]
with open("output.csv", "w") as outfile:
header = "serialnumber;date;time;voltage;ignition\n"
outfile.write(header)
with pdfplumber.open(file) as pdf:
for page in pdf.pages:
for line in page.extract_text().split('\n'):
if line.strip() in skiplines:
continue
outfile.write(";".join(line.split())+"\n")
EDIT
So, JSON files in python are basically just a list of dict items (yes, that's oversimplification).
The only thing you need to change is the way you actually process the lines. The actual meat of the logic doesn't change...
import pdfplumber
import json
file = "Battery Voltage.pdf"
skiplines = [
"Battery Voltage",
"AM",
"PM",
"Sr No DateTIme Voltage (v) Ignition",
""
]
result = []
with pdfplumber.open(file) as pdf:
for page in pdf.pages:
for line in page.extract_text().split("\n"):
if line.strip() in skiplines:
continue
serialnumber, date, time, voltage, ignition = line.split()
result.append(
{
"serialnumber": serialnumber,
"date": date,
"time": time,
"voltage": voltage,
"ignition": ignition,
}
)
with open("output.json", "w") as outfile:
json.dump(result, outfile)
|
How to Convert PDF file into CSV file using Python Pandas
|
I have a PDF file, I need to convert it into a CSV file this is my pdf file example as link https://online.flippingbook.com/view/352975479/ the code used is
import re
import parse
import pdfplumber
import pandas as pd
from collections import namedtuple
file = "Battery Voltage.pdf"
lines = []
total_check = 0
with pdfplumber.open(file) as pdf:
pages = pdf.pages
for page in pdf.pages:
text = page.extract_text()
for line in text.split('\n'):
print(line)
with the above script I am not getting proper output, For Time column "AM" is getting in the next line. The output I am getting is like this
|
[
"It may help you to see how the surface of a pdf is displayed to the screen. so that one string of plain text is placed part by part on the display. (Here I highlight where the first AM is to be placed.\n\nAs a side issue that first AM in the file is I think at first glance encoded as this block\nBT\n/F1 12 Tf\n1 0 0 1 224.20265 754.6322 Tm\n[<001D001E>] TJ\nET\n\nWhere in that area 1D = A and 1E = M\nSo If you wish to extract each LINE as it is displayed, by far the simplest way is to use a library such as pdftotext that especially outputs each row of text as seen on page.\nThus using an attack such as tabular comma separated you can expect each AM will be given its own row. Which should by logic be \" \",AM,\" \",\" \" but some extractors should say nan,AM,nan,nan\nAs text it looks like this from just one programmable line\npdftotext -layout \"Battery Voltage.pdf\"\nThat will output \"Battery Voltage.txt\" in the same work folder\n\nThen placing that in a spreadsheet becomes\n\nNow we can export in a couple of clicks (no longer) as \"proper output\" csv along with all its oddities that csv entails.\n,,Battery Vo,ltage,\n\n\n\n\nSr No,DateT,Ime,Voltage (v),Ignition\n1,01/11/2022,00:08:10,47.15,Off\n,AM,,,\n2,01/11/2022,00:23:10,47.15,Off\n,AM,,,\n3,01/11/2022,00:38:10,47.15,Off\n,AM,,,\n4,01/11/2022,00:58:10,47.15,Off\n,AM,,,\n5,01/11/2022,01:18:10,47.15,Off\n,AM,,,\n6,01/11/2022,01:33:10,47.15,Off\n,AM,,,\n7,01/11/2022,01:48:10,47.15,Off\n,AM,,,\n8,01/11/2022,02:03:10,47.15,Off\n,AM,,,\n9,01/11/2022,02:18:10,47.15,Off\n,AM,,,\n10,01/11/2022,02:37:12,47.15,Off\n,AM,,,\n\nSo, if the edits were not done before csv generation it is simpler to post process in an editor, like this html page (no need for more apps)\n,,Battery,Voltage,\nSr No,Date,Time,Voltage (v),Ignition\n1,01/11/2022,00:08:10,47.15,Off,AM,,,\n2,01/11/2022,00:23:10,47.15,Off,AM,,,\n3,01/11/2022,00:38:10,47.15,Off,AM,,,\n4,01/11/2022,00:58:10,47.15,Off,AM,,,\n5,01/11/2022,01:18:10,47.15,Off,AM,,,\n6,01/11/2022,01:33:10,47.15,Off,AM,,,\n7,01/11/2022,01:48:10,47.15,Off,AM,,,\n8,01/11/2022,02:03:10,47.15,Off,AM,,,\n9,01/11/2022,02:18:10,47.15,Off,AM,,,\n10,01/11/2022,02:37:12,47.15,Off,AM,,,\n\nThen on re-import it looks more human generated\n\nIn discussions it was confirmed all that's desired is a means to a structured list and first parse using\npdftotext -layout -nopgbrk -x 0 -y 60 -W 800 -H 800 -fixed 6 \"Battery Voltage.pdf\" &type \"battery voltage.txt\"|findstr \"O\">battery.txt\nwill output regulated data columns for framing, with a fixed headline or splitting or otherwise using cleaned data.\n 1 01-11-2022 00:08:10 47.15 Off\n 2 01-11-2022 00:23:10 47.15 Off\n 3 01-11-2022 00:38:10 47.15 Off\n 4 01-11-2022 00:58:10 47.15 Off\n 5 01-11-2022 01:18:10 47.15 Off\n...\n 32357 24-11-2022 17:48:43 45.40 On\n 32358 24-11-2022 17:48:52 44.51 On\n 32359 24-11-2022 17:48:55 44.51 On\n 32360 24-11-2022 17:48:58 44.51 On\n 32361 24-11-2022 17:48:58 44.51 On\n\nAt this stage we can use text handling such as csv or add json brackets\nfor /f \"tokens=1,2,3,4,5 delims= \" %%a In ('Findstr /C:\"O\" battery.txt') do echo csv is \"%%a,%%b,%%c,%%d,%%e\">output.txt\n...\ncsv is \"32357,24-11-2022,17:48:43,45.40,On\"\ncsv is \"32358,24-11-2022,17:48:52,44.51,On\"\ncsv is \"32359,24-11-2022,17:48:55,44.51,On\"\ncsv is \"32360,24-11-2022,17:48:58,44.51,On\"\ncsv is \"32361,24-11-2022,17:48:58,44.51,On\"\n\nSo the request is for JSON (not my forte so you may need to improve on my code as I dont know what mongo expects)\nhere I drop a pdf onto a battery.bat\n\n{\"line_id\":1,\"created\":{\"date\":\"01-11-2022\"},{\"time\":\"00:08:10\"},{\"Voltage\":\"47.15\"},{\"State\",\"Off\"}}\n{\"line_id\":2,\"created\":{\"date\":\"01-11-2022\"},{\"time\":\"00:23:10\"},{\"Voltage\":\"47.15\"},{\"State\",\"Off\"}}\n{\"line_id\":3,\"created\":{\"date\":\"01-11-2022\"},{\"time\":\"00:38:10\"},{\"Voltage\":\"47.15\"},{\"State\",\"Off\"}}\n{\"line_id\":4,\"created\":{\"date\":\"01-11-2022\"},{\"time\":\"00:58:10\"},{\"Voltage\":\"47.15\"},{\"State\",\"Off\"}}\n{\"line_id\":5,\"created\":{\"date\":\"01-11-2022\"},{\"time\":\"01:18:10\"},{\"Voltage\":\"47.15\"},{\"State\",\"Off\"}}\n{\"line_id\":6,\"created\":{\"date\":\"01-11-2022\"},{\"time\":\"01:33:10\"},{\"Voltage\":\"47.15\"},{\"State\",\"Off\"}}\n{\"line_id\":7,\"created\":{\"date\":\"01-11-2022\"},{\"time\":\"01:48:10\"},{\"Voltage\":\"47.15\"},{\"State\",\"Off\"}}\n{\"line_id\":8,\"created\":{\"date\":\"01-11-2022\"},{\"time\":\"02:03:10\"},{\"Voltage\":\"47.15\"},{\"State\",\"Off\"}}\n{\"line_id\":9,\"created\":{\"date\":\"01-11-2022\"},{\"time\":\"02:18:10\"},{\"Voltage\":\"47.15\"},{\"State\",\"Off\"}}\n{\"line_id\":10,\"created\":{\"date\":\"01-11-2022\"},{\"time\":\"02:37:12\"},{\"Voltage\":\"47.15\"},{\"State\",\"Off\"}}\n\nit is a bit slow as running in pure console so lets run it blinder by add @, it will still take time as we are working in plain text, so do expect a significant delay for 32,000+ lines = 2+1/2 minutes on my kit\npdftotext -layout -nopgbrk -x 0 -y 60 -W 700 -H 800 -fixed 8 \"%~1\" battery.txt\n\necho Heading however you wish it for json perhaps just opener [ but note only one redirect chevron >\"%~dpn1.txt\"\n\nfor /f \"tokens=1,2,3,4,5 delims= \" %%a In ('Findstr /C:\"O\" battery.txt') do @echo \"%%a\": { \"Date\": \"%%b\", \"Time\": \"%%c\", \"Voltage\": %%d, \"Ignition\": \"%%e\" },>>\"%~dpn1.txt\"\nREM another json style could be { \"Line_Id\": %%a, \"Date\": \"%%b\", \"Time\": \"%%c\", \"Voltage\": %%d, \"Ignition\": \"%%e\" },\nREM another for an array can simply be [%%a,\"%%b\",\"%%c\",%%d,\"%%e\" ],\n\necho Tailing however you wish it for json perhaps just final closer ] but note double chevron >>\"%~dpn1.txt\"\n\n\nTo see progress change @echo { to @echo %%a&echo {\nThus, after a minute or so\n however, it tends to add an extra minute for all that display activity! before the window closes as a sign of completion.\n",
"For cases like these, build a parser that converts the unusable data into something you can use.\nLogic below converts that exact file to a CSV, but will only work with that specific file contents.\nNote that for this specific file you can ignore the AM/PM as the time is in 24h format.\nimport pdfplumber\n\n\nfile = \"Battery Voltage.pdf\"\nskiplines = [\n \"Battery Voltage\",\n \"AM\",\n \"PM\",\n \"Sr No DateTIme Voltage (v) Ignition\",\n \"\"\n]\n\n\nwith open(\"output.csv\", \"w\") as outfile:\n header = \"serialnumber;date;time;voltage;ignition\\n\"\n outfile.write(header)\n with pdfplumber.open(file) as pdf:\n for page in pdf.pages:\n for line in page.extract_text().split('\\n'):\n if line.strip() in skiplines:\n continue\n outfile.write(\";\".join(line.split())+\"\\n\")\n\n\nEDIT\nSo, JSON files in python are basically just a list of dict items (yes, that's oversimplification).\nThe only thing you need to change is the way you actually process the lines. The actual meat of the logic doesn't change...\nimport pdfplumber\nimport json\n\n\nfile = \"Battery Voltage.pdf\"\nskiplines = [\n \"Battery Voltage\",\n \"AM\",\n \"PM\",\n \"Sr No DateTIme Voltage (v) Ignition\",\n \"\"\n]\nresult = []\n\n\nwith pdfplumber.open(file) as pdf:\n for page in pdf.pages:\n for line in page.extract_text().split(\"\\n\"):\n if line.strip() in skiplines:\n continue\n serialnumber, date, time, voltage, ignition = line.split()\n result.append(\n {\n \"serialnumber\": serialnumber,\n \"date\": date,\n \"time\": time,\n \"voltage\": voltage,\n \"ignition\": ignition,\n }\n )\n\nwith open(\"output.json\", \"w\") as outfile:\n json.dump(result, outfile)\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"csv",
"pandas",
"pdf",
"pdfplumber",
"python"
] |
stackoverflow_0074579676_csv_pandas_pdf_pdfplumber_python.txt
|
Q:
How to select a range of the data in urls to views in Django
path('<int:book_id>/',views.detail, name = 'detail')
How can I modify this line of code to can select the digits that can be used instead of sending any number?
as I want the range to be [1 - 5]
path('<int:book_id>[1-5]/',views.detail, name = 'detail'),
I've tried this but not correct
A:
You need to check it in the view itself.
def detail(request, book_id):
if book_id < 1 or book_id > 5:
# do something here when the number is not between or equals 1-5.
raise PermissionDenied()
|
How to select a range of the data in urls to views in Django
|
path('<int:book_id>/',views.detail, name = 'detail')
How can I modify this line of code to can select the digits that can be used instead of sending any number?
as I want the range to be [1 - 5]
path('<int:book_id>[1-5]/',views.detail, name = 'detail'),
I've tried this but not correct
|
[
"You need to check it in the view itself.\ndef detail(request, book_id):\n if book_id < 1 or book_id > 5:\n # do something here when the number is not between or equals 1-5.\n raise PermissionDenied()\n\n\n"
] |
[
0
] |
[] |
[] |
[
"database",
"django_urls",
"django_views",
"python",
"python_re"
] |
stackoverflow_0074582395_database_django_urls_django_views_python_python_re.txt
|
Q:
How to display multiple images which numbers of image not same for every attempt
I want to display some images with matplotlib with fig.add_subplot but for some attempts I faced some errors like below:
Traceback (most recent call last):
File "/home/---/Documents/---/---/dataset.py", line 134, in <module>
display_dicom(dicom,target["mask"])
File "/home/---/Documents/---/---/dataset.py", line 123, in display_dicom
fig.add_subplot(rows,cols,i+2)
File "/home/---/.pyenv/versions/3.8.13/envs/---/lib/python3.8/site-packages/matplotlib/figure.py", line 745, in add_subplot
ax = subplot_class_factory(projection_class)(self, *args, **pkw)
File "/home/---/.pyenv/versions/3.8.13/envs/---/lib/python3.8/site-packages/matplotlib/axes/_subplots.py", line 36, in __init__
self.set_subplotspec(SubplotSpec._from_subplot_args(fig, args))
File "/home/---/.pyenv/versions/3.8.13/envs/---/lib/python3.8/site-packages/matplotlib/gridspec.py", line 612, in _from_subplot_args
raise ValueError(
ValueError: num must be 1 <= num <= 2, not 3
Traceback (most recent call last):
File "/home/---/Documents/---/---/dataset.py", line 133, in <module>
display_dicom(dicom,target["mask"])
File "/home/---/Documents/---/---/dataset.py", line 123, in display_dicom
plt.imshow(mask[i],cmap=plt.cm.bone)
IndexError: index 69 is out of bounds for dimension 0 with size 69
I want to compute row and col in plt.figure automatically. What is the formula that doesn't crash the code?
I tried the following func to display it.
dicom and mask are torch.tensors. When I select the row and col by hand, it works well.
def display_dicom(dicom,mask):
count,width,height = mask.shape
if count == 0:
count = 1
fig = plt.figure(figsize=(10,10))
rows= int(math.sqrt(count)+1)
cols = int(math.sqrt(count)+1)
fig.add_subplot(rows,cols, 1)
plt.imshow(dicom, cmap=plt.cm.bone) # set the color map to bone
plt.title("dicom")
for i in range(2,count+2):
fig.add_subplot(rows,cols,i)
plt.imshow(mask[i],cmap=plt.cm.bone)
plt.title(f"mask {i+1}")
plt.show()
Sample plots are how I want to get the plot:
A:
I rearrange the display_dicom function as below. It is works fine now. It's not the best solution.
def display_dicom(dicom,mask):
count,width,height = mask.shape
if count == 0:
count = 1 # np.zeros empty mask
number_of_images = count + 1 # masks + dicom
fig = plt.figure(figsize=(10,10))
rows= math.ceil(math.sqrt(number_of_images))
cols = rows
fig.add_subplot(rows,cols, 1)
plt.imshow(dicom, cmap=plt.cm.bone) # set the color map to bone
plt.title("dicom")
for i in range(count):
fig.add_subplot(rows,cols,i+2)
plt.imshow(mask[i],cmap=plt.cm.bone)
plt.title(f"mask {i+1}")
plt.show()
|
How to display multiple images which numbers of image not same for every attempt
|
I want to display some images with matplotlib with fig.add_subplot but for some attempts I faced some errors like below:
Traceback (most recent call last):
File "/home/---/Documents/---/---/dataset.py", line 134, in <module>
display_dicom(dicom,target["mask"])
File "/home/---/Documents/---/---/dataset.py", line 123, in display_dicom
fig.add_subplot(rows,cols,i+2)
File "/home/---/.pyenv/versions/3.8.13/envs/---/lib/python3.8/site-packages/matplotlib/figure.py", line 745, in add_subplot
ax = subplot_class_factory(projection_class)(self, *args, **pkw)
File "/home/---/.pyenv/versions/3.8.13/envs/---/lib/python3.8/site-packages/matplotlib/axes/_subplots.py", line 36, in __init__
self.set_subplotspec(SubplotSpec._from_subplot_args(fig, args))
File "/home/---/.pyenv/versions/3.8.13/envs/---/lib/python3.8/site-packages/matplotlib/gridspec.py", line 612, in _from_subplot_args
raise ValueError(
ValueError: num must be 1 <= num <= 2, not 3
Traceback (most recent call last):
File "/home/---/Documents/---/---/dataset.py", line 133, in <module>
display_dicom(dicom,target["mask"])
File "/home/---/Documents/---/---/dataset.py", line 123, in display_dicom
plt.imshow(mask[i],cmap=plt.cm.bone)
IndexError: index 69 is out of bounds for dimension 0 with size 69
I want to compute row and col in plt.figure automatically. What is the formula that doesn't crash the code?
I tried the following func to display it.
dicom and mask are torch.tensors. When I select the row and col by hand, it works well.
def display_dicom(dicom,mask):
count,width,height = mask.shape
if count == 0:
count = 1
fig = plt.figure(figsize=(10,10))
rows= int(math.sqrt(count)+1)
cols = int(math.sqrt(count)+1)
fig.add_subplot(rows,cols, 1)
plt.imshow(dicom, cmap=plt.cm.bone) # set the color map to bone
plt.title("dicom")
for i in range(2,count+2):
fig.add_subplot(rows,cols,i)
plt.imshow(mask[i],cmap=plt.cm.bone)
plt.title(f"mask {i+1}")
plt.show()
Sample plots are how I want to get the plot:
|
[
"I rearrange the display_dicom function as below. It is works fine now. It's not the best solution.\ndef display_dicom(dicom,mask):\n\n count,width,height = mask.shape\n if count == 0:\n count = 1 # np.zeros empty mask\n \n number_of_images = count + 1 # masks + dicom\n\n fig = plt.figure(figsize=(10,10))\n rows= math.ceil(math.sqrt(number_of_images))\n cols = rows\n \n fig.add_subplot(rows,cols, 1)\n plt.imshow(dicom, cmap=plt.cm.bone) # set the color map to bone\n plt.title(\"dicom\")\n\n for i in range(count):\n fig.add_subplot(rows,cols,i+2)\n plt.imshow(mask[i],cmap=plt.cm.bone)\n plt.title(f\"mask {i+1}\")\n\n plt.show()\n\n\n"
] |
[
0
] |
[
"How about using fig, axes = plt.subplots(nrows = rows, ncols = cols, figsize = (10, 10)) and then you iterate over the axes and do .imshow on each one of them? axes will be a 2D array of size nrows x ncols.\n"
] |
[
-1
] |
[
"display",
"imshow",
"matplotlib",
"python",
"subplot"
] |
stackoverflow_0074546863_display_imshow_matplotlib_python_subplot.txt
|
Q:
Why does the model predict ineffectively even though the loss function is low?
I'm applying machine learning in the physics field to predict the potential of a molecule. This potential can be described as a 2d array with a shape 64*64. For convenience, I scaled the value of the potential in the range from 0 to 1.
A sample of the potential after being scaled:
My goal is to build a neural network model with Keras to predict the potential. The input of the model is some physical quantities that can be treated as a 1d array and the output is the potential that I mentioned above. The results of the model after training were great, the MAPE is less than 5%, but the test phase had a big problem on both the test dataset and trainining dataset (both of the datasets have the same distribution input).
The left one is the potential that the model predicts, the middle one is the true value, and the last one this the MAPE:
I have tried many loss functions (MAE; (1-SSIM); etc.); change the model layers to improve the model, but nothing happened.
Here is my lowest loss:
120/120 [==============================] - 3s 29ms/step - loss: 0.0534 - mape: 1.2858
The loss function:
def LOSS(y_true, y_pred):
LOSS1 = K.abs(y_pred - y_true)
LOSS1 = K.batch_flatten(LOSS1)
LOSS1 = tf.reduce_mean(LOSS1, axis=-1)
LOSS2 = 1 - tf.image.ssim(tf.reshape(y_true, [-1, NyMax, NxMax, 1]),
tf.reshape(y_pred, [-1, NyMax, NxMax, 1]), 1)
return tf.math.add(3*LOSS1, 7*LOSS2)
The model:
def create_model(in_dim,x_dim,y_dim):
H,W = int(y_dim/2), int(x_dim/2)
inputs = tf.keras.Input(shape=(in_dim,))
x = tf.keras.layers.Dense(64, activation='tanh')(inputs)
x = tf.keras.layers.Dense(H*W, activation='tanh')(x)
x = tf.keras.layers.Dropout(0.2)(x)
x = tf.keras.layers.Reshape((H,W,1))(x)
x = tf.keras.layers.Conv2DTranspose(4, kernel_size=(1,1), strides=(1,1), activation='selu', padding='same',
kernel_regularizer=regularizers.L1(1e-4), bias_regularizer=regularizers.L1(1e-4))(x)
x = tf.keras.layers.Dropout(0.2)(x)
x = tf.keras.layers.Conv2DTranspose(4, kernel_size=(4,4), strides=(2,2), activation='selu', padding='same',
kernel_regularizer=regularizers.L1(1e-4), bias_regularizer=regularizers.L1(1e-4))(x)
x = tf.keras.layers.Dropout(0.2)(x)
x = tf.keras.layers.Conv2D(1, kernel_size=(5,5), activation='relu', padding='same',
kernel_regularizer=regularizers.L1(1e-4), bias_regularizer=regularizers.L1(1e-4))(x)
outputs = tf.keras.layers.Reshape((y_dim,x_dim))(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
return model
Can anyone explain why my model is ineffective although the loss is low and how to improve it?
The loss plot:
Here is how I transform the input data:
poly = PolynomialFeatures(POLY_DEGREE) # POLY_DEGREE = 4
scaler = StandardScaler()
pca = PCA(PCA_COMPONENTS) # POLY_DEGREE = 64
X = poly.fit_transform(X)
X = scaler.fit_transform(X)
X = pca.fit_transform(X)
|
Why does the model predict ineffectively even though the loss function is low?
|
I'm applying machine learning in the physics field to predict the potential of a molecule. This potential can be described as a 2d array with a shape 64*64. For convenience, I scaled the value of the potential in the range from 0 to 1.
A sample of the potential after being scaled:
My goal is to build a neural network model with Keras to predict the potential. The input of the model is some physical quantities that can be treated as a 1d array and the output is the potential that I mentioned above. The results of the model after training were great, the MAPE is less than 5%, but the test phase had a big problem on both the test dataset and trainining dataset (both of the datasets have the same distribution input).
The left one is the potential that the model predicts, the middle one is the true value, and the last one this the MAPE:
I have tried many loss functions (MAE; (1-SSIM); etc.); change the model layers to improve the model, but nothing happened.
Here is my lowest loss:
120/120 [==============================] - 3s 29ms/step - loss: 0.0534 - mape: 1.2858
The loss function:
def LOSS(y_true, y_pred):
LOSS1 = K.abs(y_pred - y_true)
LOSS1 = K.batch_flatten(LOSS1)
LOSS1 = tf.reduce_mean(LOSS1, axis=-1)
LOSS2 = 1 - tf.image.ssim(tf.reshape(y_true, [-1, NyMax, NxMax, 1]),
tf.reshape(y_pred, [-1, NyMax, NxMax, 1]), 1)
return tf.math.add(3*LOSS1, 7*LOSS2)
The model:
def create_model(in_dim,x_dim,y_dim):
H,W = int(y_dim/2), int(x_dim/2)
inputs = tf.keras.Input(shape=(in_dim,))
x = tf.keras.layers.Dense(64, activation='tanh')(inputs)
x = tf.keras.layers.Dense(H*W, activation='tanh')(x)
x = tf.keras.layers.Dropout(0.2)(x)
x = tf.keras.layers.Reshape((H,W,1))(x)
x = tf.keras.layers.Conv2DTranspose(4, kernel_size=(1,1), strides=(1,1), activation='selu', padding='same',
kernel_regularizer=regularizers.L1(1e-4), bias_regularizer=regularizers.L1(1e-4))(x)
x = tf.keras.layers.Dropout(0.2)(x)
x = tf.keras.layers.Conv2DTranspose(4, kernel_size=(4,4), strides=(2,2), activation='selu', padding='same',
kernel_regularizer=regularizers.L1(1e-4), bias_regularizer=regularizers.L1(1e-4))(x)
x = tf.keras.layers.Dropout(0.2)(x)
x = tf.keras.layers.Conv2D(1, kernel_size=(5,5), activation='relu', padding='same',
kernel_regularizer=regularizers.L1(1e-4), bias_regularizer=regularizers.L1(1e-4))(x)
outputs = tf.keras.layers.Reshape((y_dim,x_dim))(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
return model
Can anyone explain why my model is ineffective although the loss is low and how to improve it?
The loss plot:
Here is how I transform the input data:
poly = PolynomialFeatures(POLY_DEGREE) # POLY_DEGREE = 4
scaler = StandardScaler()
pca = PCA(PCA_COMPONENTS) # POLY_DEGREE = 64
X = poly.fit_transform(X)
X = scaler.fit_transform(X)
X = pca.fit_transform(X)
|
[] |
[] |
[
"Probably your model is over-fitting the data:\nhttps://www.ibm.com/cloud/learn/overfitting#:~:text=Overfitting%20is%20a%20concept%20in,unseen%20data%2C%20defeating%20its%20purpose.\nA clear sign of over-fitting is when the training loss is very low, but the validation errors are large.\nWhy does this happen? Well, neural networks have so many degrees-of-freedom that in some cases, they \"memorize\" the training data on a point-by-point basis, but they do not build internal rules to classify the data in a physical manner.\nThe best way to overcome this is to reduce the size of the neural network, to avoid having too many redundant degrees-of-freedom that contribute to over-fitting, or to introduce regularization:\nhttps://towardsdatascience.com/l1-and-l2-regularization-methods-ce25e7fc831c?gi=519207f1e90d\nAlso, if you have any hints about a numerical or physical framework that is well-suited for your problem (for example, a special transformation for your input data), you should also consider adding it to the neural network manually. (This is recommeded in most PhD-level courses about machine learning).\n"
] |
[
-1
] |
[
"keras",
"loss_function",
"machine_learning",
"neural_network",
"python"
] |
stackoverflow_0074582277_keras_loss_function_machine_learning_neural_network_python.txt
|
Q:
How to solve ReadTimeoutError: HTTPSConnectionPool(host='pypi.python.org', port=443) with pip?
I recently need to install some packages
pip install future
pip install scikit-learn
pip install numpy
pip install scipy
I also tried by writin sudo before them but all it came up with the following errors in red lines:
Exception:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
status = self.run(options, args)
File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 290, in run
requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1198, in prepare_files
do_download,
File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1376, in unpack_url
self.session,
File "/usr/lib/python2.7/dist-packages/pip/download.py", line 572, in unpack_http_url
download_hash = _download_url(resp, link, temp_location)
File "/usr/lib/python2.7/dist-packages/pip/download.py", line 433, in _download_url
for chunk in resp_read(4096):
File "/usr/lib/python2.7/dist-packages/pip/download.py", line 421, in resp_read
chunk_size, decode_content=False):
File "/usr/lib/python2.7/dist-packages/urllib3/response.py", line 256, in stream
data = self.read(amt=amt, decode_content=decode_content)
File "/usr/lib/python2.7/dist-packages/urllib3/response.py", line 201, in read
raise ReadTimeoutError(self._pool, None, 'Read timed out.')
ReadTimeoutError: HTTPSConnectionPool(host='pypi.python.org', port=443): Read timed out.
Storing debug log for failure in /root/.pip/pip.log'
A:
Use --default-timeout=100 parameter with the install:
sudo pip install --default-timeout=100 future
A:
sudo pip install --default-timeout=100 future
or alternatively
export PIP_DEFAULT_TIMEOUT=100
worked for me on Mac OS X
A:
They are two ways to handle this issue:
sudo pip install --default-timeout=100 future
or
pip install --default-timeout=100 future
Note: If you are not superuser of your machine, the sudo pip command will not work.
A:
If you are using JetBrains PyCharm, the appropriate solution steps are :
connect to terminal/open terminal in PyCharm.
type source <path to your projects environment eg: /users/name/myapp/venv>
Run pip install <package name> or run pip3 install <package name> as per your installation
This will automatically install package for your interpreter.
A:
Just throwing this out there to avoid any confusion, for pip3 you can use
sudo pip3 install --default-timeout=100 future
A:
Upgrading pip solved the problem for me.
python -m pip install --upgrade pip
|
How to solve ReadTimeoutError: HTTPSConnectionPool(host='pypi.python.org', port=443) with pip?
|
I recently need to install some packages
pip install future
pip install scikit-learn
pip install numpy
pip install scipy
I also tried by writin sudo before them but all it came up with the following errors in red lines:
Exception:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
status = self.run(options, args)
File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 290, in run
requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1198, in prepare_files
do_download,
File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1376, in unpack_url
self.session,
File "/usr/lib/python2.7/dist-packages/pip/download.py", line 572, in unpack_http_url
download_hash = _download_url(resp, link, temp_location)
File "/usr/lib/python2.7/dist-packages/pip/download.py", line 433, in _download_url
for chunk in resp_read(4096):
File "/usr/lib/python2.7/dist-packages/pip/download.py", line 421, in resp_read
chunk_size, decode_content=False):
File "/usr/lib/python2.7/dist-packages/urllib3/response.py", line 256, in stream
data = self.read(amt=amt, decode_content=decode_content)
File "/usr/lib/python2.7/dist-packages/urllib3/response.py", line 201, in read
raise ReadTimeoutError(self._pool, None, 'Read timed out.')
ReadTimeoutError: HTTPSConnectionPool(host='pypi.python.org', port=443): Read timed out.
Storing debug log for failure in /root/.pip/pip.log'
|
[
"Use --default-timeout=100 parameter with the install:\nsudo pip install --default-timeout=100 future\n\n",
"sudo pip install --default-timeout=100 future \n\nor alternatively\nexport PIP_DEFAULT_TIMEOUT=100\n\nworked for me on Mac OS X\n",
"They are two ways to handle this issue:\nsudo pip install --default-timeout=100 future\n\nor\npip install --default-timeout=100 future\n\nNote: If you are not superuser of your machine, the sudo pip command will not work.\n",
"If you are using JetBrains PyCharm, the appropriate solution steps are :\n\nconnect to terminal/open terminal in PyCharm.\n\ntype source <path to your projects environment eg: /users/name/myapp/venv>\n\nRun pip install <package name> or run pip3 install <package name> as per your installation\n\n\nThis will automatically install package for your interpreter.\n",
"Just throwing this out there to avoid any confusion, for pip3 you can use\nsudo pip3 install --default-timeout=100 future\n\n",
"Upgrading pip solved the problem for me.\npython -m pip install --upgrade pip\n\n"
] |
[
275,
24,
5,
0,
0,
0
] |
[] |
[] |
[
"pip",
"python"
] |
stackoverflow_0043298872_pip_python.txt
|
Q:
Does the MacOS Clipboard have a path to it?
I am currently working on a python program that makes use of the clipboard. If you want to know more, I am finding a way to access clipboard history, which is very hard to find for free. I then realized I had no idea how to access the clipboard. My main question is, is there a way to access the clipboard and read what it says through python with any module? Or, does the MacOS Clipboard have a path that I can use to read the file and get the clipboard?
I only used two modules, pyperclip and clipboard. These two apparently only have the copy & paste function.
A:
In macOS, once you copy something else, the previous item disappears. macOS clipboard is designed to hold one item at a time.
To get the last clipboard item in python use this:
import pyperclip as pc
clipboard = pc.paste()
print(clipboard)
A solution to your query:
Run a code that checks the pc.paste() value periodically(e.g. every second) for any change and adds the new value to a variable/file that preserves a history of the records.
Same as number 1 but instead of adopting a periodical approach, watches pc.paste() for any change using python pdb library. It's for debugging but you can trace any change in the value of a variable using pdb.set_trace() function.
|
Does the MacOS Clipboard have a path to it?
|
I am currently working on a python program that makes use of the clipboard. If you want to know more, I am finding a way to access clipboard history, which is very hard to find for free. I then realized I had no idea how to access the clipboard. My main question is, is there a way to access the clipboard and read what it says through python with any module? Or, does the MacOS Clipboard have a path that I can use to read the file and get the clipboard?
I only used two modules, pyperclip and clipboard. These two apparently only have the copy & paste function.
|
[
"In macOS, once you copy something else, the previous item disappears. macOS clipboard is designed to hold one item at a time.\nTo get the last clipboard item in python use this:\nimport pyperclip as pc\n\nclipboard = pc.paste()\nprint(clipboard)\n\nA solution to your query:\n\nRun a code that checks the pc.paste() value periodically(e.g. every second) for any change and adds the new value to a variable/file that preserves a history of the records.\nSame as number 1 but instead of adopting a periodical approach, watches pc.paste() for any change using python pdb library. It's for debugging but you can trace any change in the value of a variable using pdb.set_trace() function.\n\n"
] |
[
2
] |
[] |
[] |
[
"clipboard",
"macos",
"pyperclip",
"python",
"python_3.x"
] |
stackoverflow_0074580872_clipboard_macos_pyperclip_python_python_3.x.txt
|
Q:
Using tempfile to insert barcodes into PDF file
I'm working on a project where I need to use one large PDF file with 100,000's of images, where I need to insert a custom/variable barcode on every nth page (conditional dependant).
The contents of the barcode will change for every insertion, for this example, let's just say based on iteration.
I've used PyMuPDF to manipulate PDFs in the past, including inserting images. I've tested inserting barcodes when they're saved to file, and have no issues.
I've used Treepoem in the past to generate custom barcodes as required, on a much smaller scale.
(This is still in planning/proof of concept phase) So my concern is that if I'll be doing this at a larger scale, I'll be limited by disk read/write speeds.
I understand that python has a tempfile library, that I've never used. I'm attempting to leverage this to generate and save barcodes to tempfiles in memory, and then insert them into the PDF file from memory, rather than from disk/file.
I've tested and confirmed that generating a barcode and saving it to file allows me to insert into the PDF file as required. Below example:
import fitz
import treepoem
barcode_file = treepoem.generate_barcode(
barcode_type='datamatrixrectangular',
data='10000010'
).convert('1').save('barcode_file.jpg') # Convert('1') forces monochrome, reducing file size.
pdf_file = fitz.open() # Creating a new file for this example.
pdf_file.new_page() # Inserting a new blank page.
page = pdf_file[0]
rect = fitz.Rect(70, 155, 200, 230) # Generic area defined, required to insert barcode into. (x0, y0, x1, y1)
page.insert_image(rect, filename='barcode_file.jpg')
pdf_file.save('example_pdf_with_barcode.pdf')
When trying to implement tempfile to remove saving to file, I'm not sure where to utilise it.
I've tried creating a new tempfile object, inserting the barcode image into it.
import fitz
import tempfile
import treepoem
barcode_contents = treepoem.generate_barcode(
barcode_type='datamatrixrectangular',
data='10000010'
).convert('1')
barcode_tempfile = tempfile.TemporaryFile()
barcode_tempfile.write(b'{barcode_contents}') # Like f-string, with binary?
barcode_tempfile.seek(0) # Required, not understood.
pdf_file = fitz.open() # Creating a new file for this example.
pdf_file.new_page() # Inserting a new blank page.
page = pdf_file[0]
rect = fitz.Rect(70, 155, 200, 230) # Generic area defined, required to insert barcode into. (x0, y0, x1, y1)
page.insert_image(rect, filename=barcode_tempfile)
pdf_file.save('example_pdf_with_barcode.pdf')
Which returns a permission based error:
File "<redacted>\example.py", line 20, in <module>
page.insert_image(rect, filename=barcode_tempfile)
File "<redacted>\venv\Lib\site-packages\fitz\utils.py", line 352, in insert_image
xref, digests = page._insert_image(
^^^^^^^^^^^^^^^^^^^
File "<redacted>\venv\Lib\site-packages\fitz\fitz.py", line 6520, in _insert_image
return _fitz.Page__insert_image(self, filename, pixmap, stream, imask, clip, overlay, rotate, keep_proportion, oc, width, height, xref, alpha, _imgname, digests)
RuntimeError: cannot open <redacted>\AppData\Local\Temp\tmpr_98wni9: Permission denied
I've looked for said temp file in the specified directory, which can't be found. So I can't figure out how to trouble shoot this.
Treepoem's barcode generator also has a save() method, where you can typically save to file. I've tried to save to a tempfile instead, as below:
import fitz
import tempfile
import treepoem
treepoem.generate_barcode(
barcode_type='datamatrixrectangular',
data='10000010'
).convert('1').save(tempfile.TemporaryFile('barcode_tempfile'))
pdf_file = fitz.open() # Creating a new file for this example.
pdf_file.new_page() # Inserting a new blank page.
page = pdf_file[0]
rect = fitz.Rect(70, 155, 200, 230) # Generic area defined, required to insert barcode into. (x0, y0, x1, y1)
page.insert_image(rect, filename=barcode_tempfile)
pdf_file.save('example_pdf_with_barcode.pdf')
Which results in the below error:
File "<redacted>\example.py", line 8, in <module>
).convert('1').save(tempfile.TemporaryFile('barcode_tempfile'))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<redacted>\AppData\Local\Programs\Python\Python311\Lib\tempfile.py", line 563, in NamedTemporaryFile
file = _io.open(dir, mode, buffering=buffering,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid mode: 'barcode_tempfile'
So I'm unsure if I can save to a tempfile via this method.
Would anyone be able to explain if this is possible, how best to tackle it?
(Currently using python 3.11)
Thanks,
A:
Your problems are in the area of tempfile handling. Instead of going into detail, I suggest to stick with Pillow and use its facilities exclusively:
convert the PIL image to a JPEG / PNG as you did, but let PIL save to a memory file
insert that memory image using PyMuPDF
import io # need this for memory output
fp = io.BytesIO() # memory binary file
treepoem.generate_barcode(
barcode_type='datamatrixrectangular',
data='10000010'
).convert('1').save(fp, "JPEG")) # write image to memory
# now insert image into page using PyMuPDF
# fp.getvalue() delivers the image content in memory
page.insert_image(rect, stream=fp.getvalue())
|
Using tempfile to insert barcodes into PDF file
|
I'm working on a project where I need to use one large PDF file with 100,000's of images, where I need to insert a custom/variable barcode on every nth page (conditional dependant).
The contents of the barcode will change for every insertion, for this example, let's just say based on iteration.
I've used PyMuPDF to manipulate PDFs in the past, including inserting images. I've tested inserting barcodes when they're saved to file, and have no issues.
I've used Treepoem in the past to generate custom barcodes as required, on a much smaller scale.
(This is still in planning/proof of concept phase) So my concern is that if I'll be doing this at a larger scale, I'll be limited by disk read/write speeds.
I understand that python has a tempfile library, that I've never used. I'm attempting to leverage this to generate and save barcodes to tempfiles in memory, and then insert them into the PDF file from memory, rather than from disk/file.
I've tested and confirmed that generating a barcode and saving it to file allows me to insert into the PDF file as required. Below example:
import fitz
import treepoem
barcode_file = treepoem.generate_barcode(
barcode_type='datamatrixrectangular',
data='10000010'
).convert('1').save('barcode_file.jpg') # Convert('1') forces monochrome, reducing file size.
pdf_file = fitz.open() # Creating a new file for this example.
pdf_file.new_page() # Inserting a new blank page.
page = pdf_file[0]
rect = fitz.Rect(70, 155, 200, 230) # Generic area defined, required to insert barcode into. (x0, y0, x1, y1)
page.insert_image(rect, filename='barcode_file.jpg')
pdf_file.save('example_pdf_with_barcode.pdf')
When trying to implement tempfile to remove saving to file, I'm not sure where to utilise it.
I've tried creating a new tempfile object, inserting the barcode image into it.
import fitz
import tempfile
import treepoem
barcode_contents = treepoem.generate_barcode(
barcode_type='datamatrixrectangular',
data='10000010'
).convert('1')
barcode_tempfile = tempfile.TemporaryFile()
barcode_tempfile.write(b'{barcode_contents}') # Like f-string, with binary?
barcode_tempfile.seek(0) # Required, not understood.
pdf_file = fitz.open() # Creating a new file for this example.
pdf_file.new_page() # Inserting a new blank page.
page = pdf_file[0]
rect = fitz.Rect(70, 155, 200, 230) # Generic area defined, required to insert barcode into. (x0, y0, x1, y1)
page.insert_image(rect, filename=barcode_tempfile)
pdf_file.save('example_pdf_with_barcode.pdf')
Which returns a permission based error:
File "<redacted>\example.py", line 20, in <module>
page.insert_image(rect, filename=barcode_tempfile)
File "<redacted>\venv\Lib\site-packages\fitz\utils.py", line 352, in insert_image
xref, digests = page._insert_image(
^^^^^^^^^^^^^^^^^^^
File "<redacted>\venv\Lib\site-packages\fitz\fitz.py", line 6520, in _insert_image
return _fitz.Page__insert_image(self, filename, pixmap, stream, imask, clip, overlay, rotate, keep_proportion, oc, width, height, xref, alpha, _imgname, digests)
RuntimeError: cannot open <redacted>\AppData\Local\Temp\tmpr_98wni9: Permission denied
I've looked for said temp file in the specified directory, which can't be found. So I can't figure out how to trouble shoot this.
Treepoem's barcode generator also has a save() method, where you can typically save to file. I've tried to save to a tempfile instead, as below:
import fitz
import tempfile
import treepoem
treepoem.generate_barcode(
barcode_type='datamatrixrectangular',
data='10000010'
).convert('1').save(tempfile.TemporaryFile('barcode_tempfile'))
pdf_file = fitz.open() # Creating a new file for this example.
pdf_file.new_page() # Inserting a new blank page.
page = pdf_file[0]
rect = fitz.Rect(70, 155, 200, 230) # Generic area defined, required to insert barcode into. (x0, y0, x1, y1)
page.insert_image(rect, filename=barcode_tempfile)
pdf_file.save('example_pdf_with_barcode.pdf')
Which results in the below error:
File "<redacted>\example.py", line 8, in <module>
).convert('1').save(tempfile.TemporaryFile('barcode_tempfile'))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<redacted>\AppData\Local\Programs\Python\Python311\Lib\tempfile.py", line 563, in NamedTemporaryFile
file = _io.open(dir, mode, buffering=buffering,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid mode: 'barcode_tempfile'
So I'm unsure if I can save to a tempfile via this method.
Would anyone be able to explain if this is possible, how best to tackle it?
(Currently using python 3.11)
Thanks,
|
[
"Your problems are in the area of tempfile handling. Instead of going into detail, I suggest to stick with Pillow and use its facilities exclusively:\n\nconvert the PIL image to a JPEG / PNG as you did, but let PIL save to a memory file\ninsert that memory image using PyMuPDF\n\nimport io # need this for memory output\nfp = io.BytesIO() # memory binary file\ntreepoem.generate_barcode(\n barcode_type='datamatrixrectangular',\n data='10000010'\n).convert('1').save(fp, \"JPEG\")) # write image to memory\n\n# now insert image into page using PyMuPDF\n# fp.getvalue() delivers the image content in memory\npage.insert_image(rect, stream=fp.getvalue())\n\n"
] |
[
1
] |
[] |
[] |
[
"barcode",
"pdf",
"python",
"temporary_files"
] |
stackoverflow_0074518716_barcode_pdf_python_temporary_files.txt
|
Q:
Python: How to add value to a specific excel sheet using openpyxl?
So I wanted to add a value to a specific sheet in this case we have 2 sheets, Student Profile and Student Grades
from openpyxl import load_workbook
file = load_workbook("Registry.xlsx")
sheet = file.active
sheet.create_sheet("Student Grades")
#Student Profile
sheet["A1"] = "ID No.:"
sheet["B1"] = "Last Name:"
sheet["C1"] = "First Name:"
sheet["D1"] = "Middle Name:"
sheet["E1"] = "Sex:"
sheet["F1"] = "Date of Birth:"
file.save("Registry.xlsx")
but if we do it again with for Student Grades it just overrides the previous values of Student Profile since it stays in the sheet1
file = load_workbook("Registry.xlsx")
sheet = file.active
sheet["A1"] = "ID No:"
sheet["B1"] = "Math"
sheet["C1"] = "Science:"
sheet["D1"] = "English"
file.save("Registry.xlsx")
I tried to do:
sheet = file["Student Grades"].active
#or
sheet["Student Grades", "A1"] = "ID No."
but it returns as an error. But I noticed, if you accessed sheet 2, Student Grades, using Excel and saved before exiting. It places the value on sheet 2 instead 1. The problem is I need it to be fully automated so I can't access excel beforehand.
Edit: This is small part of a project with CRUD functions where we're restricted from using databases like sql. So we have to resort to excel instead. Since it have CRUD functions, excel file needs to be constantly updating when you have a added value to it. So i have to get that specific sheet and edit the cell values within it
A:
You need to create a sheet for the profiles with Workbook.create_sheet as you did for the grades.
Try this :
from openpyxl import load_workbook
wb = load_workbook("Registry.xlsx")
#Student Profile
ws_sp = wb.create_sheet("Student Profiles")
ws_sp["A1"] = "ID No.:"
ws_sp["B1"] = "Last Name:"
ws_sp["C1"] = "First Name:"
ws_sp["D1"] = "Middle Name:"
ws_sp["E1"] = "Sex:"
ws_sp["F1"] = "Date of Birth:"
#Student Grades
ws_sg = wb.create_sheet("Student Grades")
ws_sg["A1"] = "ID No:"
ws_sg["B1"] = "Math"
ws_sg["C1"] = "Science:"
ws_sg["D1"] = "English"
wb.save("Registry.xlsx")
|
Python: How to add value to a specific excel sheet using openpyxl?
|
So I wanted to add a value to a specific sheet in this case we have 2 sheets, Student Profile and Student Grades
from openpyxl import load_workbook
file = load_workbook("Registry.xlsx")
sheet = file.active
sheet.create_sheet("Student Grades")
#Student Profile
sheet["A1"] = "ID No.:"
sheet["B1"] = "Last Name:"
sheet["C1"] = "First Name:"
sheet["D1"] = "Middle Name:"
sheet["E1"] = "Sex:"
sheet["F1"] = "Date of Birth:"
file.save("Registry.xlsx")
but if we do it again with for Student Grades it just overrides the previous values of Student Profile since it stays in the sheet1
file = load_workbook("Registry.xlsx")
sheet = file.active
sheet["A1"] = "ID No:"
sheet["B1"] = "Math"
sheet["C1"] = "Science:"
sheet["D1"] = "English"
file.save("Registry.xlsx")
I tried to do:
sheet = file["Student Grades"].active
#or
sheet["Student Grades", "A1"] = "ID No."
but it returns as an error. But I noticed, if you accessed sheet 2, Student Grades, using Excel and saved before exiting. It places the value on sheet 2 instead 1. The problem is I need it to be fully automated so I can't access excel beforehand.
Edit: This is small part of a project with CRUD functions where we're restricted from using databases like sql. So we have to resort to excel instead. Since it have CRUD functions, excel file needs to be constantly updating when you have a added value to it. So i have to get that specific sheet and edit the cell values within it
|
[
"You need to create a sheet for the profiles with Workbook.create_sheet as you did for the grades.\nTry this :\nfrom openpyxl import load_workbook\n\nwb = load_workbook(\"Registry.xlsx\")\n\n#Student Profile\nws_sp = wb.create_sheet(\"Student Profiles\")\nws_sp[\"A1\"] = \"ID No.:\"\nws_sp[\"B1\"] = \"Last Name:\"\nws_sp[\"C1\"] = \"First Name:\"\nws_sp[\"D1\"] = \"Middle Name:\"\nws_sp[\"E1\"] = \"Sex:\"\nws_sp[\"F1\"] = \"Date of Birth:\"\n\n#Student Grades\nws_sg = wb.create_sheet(\"Student Grades\")\nws_sg[\"A1\"] = \"ID No:\"\nws_sg[\"B1\"] = \"Math\"\nws_sg[\"C1\"] = \"Science:\"\nws_sg[\"D1\"] = \"English\"\n\nwb.save(\"Registry.xlsx\")\n\n"
] |
[
0
] |
[] |
[] |
[
"excel",
"openpyxl",
"python"
] |
stackoverflow_0074582258_excel_openpyxl_python.txt
|
Q:
Openpyxl chart axis in percent
I'm creating charts in excel using openpyxl and I want some of my charts to have y-axes with the units in percent. Is this possible in openpyxl? It's quite easy in xlsxwriter, but I can't figure out how to do it in openpyxl. The code below is for a chart with two y-axes.
Thanks!
Edit:
Turns out it was as simple as changing the format of the y_axis, at least for this problem.
c2.y_axis.number_format = '0%'
def line_chart_2axis(sheet_name, file_name):
font = Font(color = "000000", size = 8.5, name = 'Avenir Next Condensed Regular')
c1 = LineChart()
data1 = Reference(data_sheet, min_col=3, min_row=1, max_col=3, max_row=len(df1)+1)
dates = Reference(data_sheet, min_col=1, min_row=2, max_col=1, max_row=len(df1)+1)
c1.add_data(data1, titles_from_data=True)
c1.title = "Title"
c1.style = 5
c1.y_axis.title = 'Y Axis 1'
c1.x_axis.number_format = 'Mmm-YYYY'
c1.set_categories(dates)
c1.y_axis.majorGridlines = None
c1.legend.position = 'b'
s1 = c1.series[0]
s1.graphicalProperties.line.width = 14000
s1.graphicalProperties.line.solidFill = "8989ff"
c2 = LineChart()
data2 = Reference(data_sheet, min_col=2, min_row=1, max_col=2, max_row=len(df1)+1)
c2.add_data(data2, titles_from_data=True)
c2.y_axis.axId = 200
c2.y_axis.title = "Y Axis 2"
c2.y_axis.crosses = "max"
c2.y_axis.majorGridlines = None
s2 = c2.series[0]
s2.graphicalProperties.line.width = 14000
s2.graphicalProperties.line.solidFill = "000062"
c1 += c2
sheet.add_chart(c1, "B2")
A:
I tried the following code and it worked for me
c1 .y_axis.number_format = '0%'
|
Openpyxl chart axis in percent
|
I'm creating charts in excel using openpyxl and I want some of my charts to have y-axes with the units in percent. Is this possible in openpyxl? It's quite easy in xlsxwriter, but I can't figure out how to do it in openpyxl. The code below is for a chart with two y-axes.
Thanks!
Edit:
Turns out it was as simple as changing the format of the y_axis, at least for this problem.
c2.y_axis.number_format = '0%'
def line_chart_2axis(sheet_name, file_name):
font = Font(color = "000000", size = 8.5, name = 'Avenir Next Condensed Regular')
c1 = LineChart()
data1 = Reference(data_sheet, min_col=3, min_row=1, max_col=3, max_row=len(df1)+1)
dates = Reference(data_sheet, min_col=1, min_row=2, max_col=1, max_row=len(df1)+1)
c1.add_data(data1, titles_from_data=True)
c1.title = "Title"
c1.style = 5
c1.y_axis.title = 'Y Axis 1'
c1.x_axis.number_format = 'Mmm-YYYY'
c1.set_categories(dates)
c1.y_axis.majorGridlines = None
c1.legend.position = 'b'
s1 = c1.series[0]
s1.graphicalProperties.line.width = 14000
s1.graphicalProperties.line.solidFill = "8989ff"
c2 = LineChart()
data2 = Reference(data_sheet, min_col=2, min_row=1, max_col=2, max_row=len(df1)+1)
c2.add_data(data2, titles_from_data=True)
c2.y_axis.axId = 200
c2.y_axis.title = "Y Axis 2"
c2.y_axis.crosses = "max"
c2.y_axis.majorGridlines = None
s2 = c2.series[0]
s2.graphicalProperties.line.width = 14000
s2.graphicalProperties.line.solidFill = "000062"
c1 += c2
sheet.add_chart(c1, "B2")
|
[
"I tried the following code and it worked for me\nc1 .y_axis.number_format = '0%'\n"
] |
[
0
] |
[] |
[] |
[
"charts",
"excel",
"openpyxl",
"python"
] |
stackoverflow_0038620551_charts_excel_openpyxl_python.txt
|
Q:
Try... except is wrong
I was working on a function that test functions and I found that y try except was wrong at all... In fact, when I am trying to test a sorting function (the one by selection) it returns me that the index was out of range and it's not the case when I try the function independently with the same list...
Here is the code :
def verifyList(L: list) -> bool:
for elm in range(len(L)):
if L[elm] > L[elm + 1]:
return False
#
return True
def tri_selection(L: list) -> list:
"""
Recupere un element et l'échange avec le un plus grand
"""
assert type(L) == list
for i in range(len(L)):
for j in range(len(L)):
if L[i] <= L[j]:
L[j], L[i] = L[i], L[j]
#
#
#
return L
Other functions that are not written because it's unnecessary...
def __test__(L: list) -> str:
assert type(L) == list
functionsToTry = [tri_selection]
for function in functionsToTry:
try:
if verifyList(function(L)) == True:
print('[✓] ' + str(function.__name__) + ' : worked successfuly')
else:
print('[≃] ' + str(function.__name__) + ' : do not worked successfuly')
continue
except Exception as error:
print('[✕] ' + str(function.__name__) + ' : ' + str(error))
else:
print(function(L))
__test__([3, 2, 1])
If you have an idea I'll be glad to know it,
Thx
A:
if L[elm] > L[elm + 1]: gives a list index out of range error when elm == len(L) - 1. The easiest fix is to change verifyList to:
def verifyList(L: list) -> bool:
return L == sorted(L)
With this change your function passes the test.
|
Try... except is wrong
|
I was working on a function that test functions and I found that y try except was wrong at all... In fact, when I am trying to test a sorting function (the one by selection) it returns me that the index was out of range and it's not the case when I try the function independently with the same list...
Here is the code :
def verifyList(L: list) -> bool:
for elm in range(len(L)):
if L[elm] > L[elm + 1]:
return False
#
return True
def tri_selection(L: list) -> list:
"""
Recupere un element et l'échange avec le un plus grand
"""
assert type(L) == list
for i in range(len(L)):
for j in range(len(L)):
if L[i] <= L[j]:
L[j], L[i] = L[i], L[j]
#
#
#
return L
Other functions that are not written because it's unnecessary...
def __test__(L: list) -> str:
assert type(L) == list
functionsToTry = [tri_selection]
for function in functionsToTry:
try:
if verifyList(function(L)) == True:
print('[✓] ' + str(function.__name__) + ' : worked successfuly')
else:
print('[≃] ' + str(function.__name__) + ' : do not worked successfuly')
continue
except Exception as error:
print('[✕] ' + str(function.__name__) + ' : ' + str(error))
else:
print(function(L))
__test__([3, 2, 1])
If you have an idea I'll be glad to know it,
Thx
|
[
"if L[elm] > L[elm + 1]: gives a list index out of range error when elm == len(L) - 1. The easiest fix is to change verifyList to:\ndef verifyList(L: list) -> bool:\n return L == sorted(L)\n\nWith this change your function passes the test.\n"
] |
[
2
] |
[] |
[] |
[
"debugging",
"python",
"try_except"
] |
stackoverflow_0074581818_debugging_python_try_except.txt
|
Q:
updating a nested dictionary getting ReferenceError: weakly-referenced object no longer exists
I am connecting to my mongodb using pymongo and trying to append to a nested dictionary using the code:
myquery = User.objects.filter(username=current_user)
my_dict = myquery[0]['spare_2']
my_dict[quiz_id] = {'question1': 9, 'question2': 9, 'question3': 9, 'question4': 9, 'question5': 9, 'question6': 9, 'question7': 9, 'question8': 9, 'question9': 9, 'question10': 9}
User.objects(username=current_user).update(spare_2=my_dict)
I am getting the error:
How can I solve this? I'm a home coding enthusiast so not very knowledgeable on why this is happening, thanks
A:
I changed the way I was updating the dictionary and it solved the problem:
myquery = User.objects.filter(username=current_user)
my_dict = myquery[0]['spare_2']
append_dict = {quiz_id: 9, 'question2': 9, 'question3': 9, 'question4': 9, 'question5': 9, 'question6': 9, 'question7': 9, 'question8': 9, 'question9': 9, 'question10': 9}
new_dict = my_dict | append_dict
User.objects(username=current_user).update(spare_2=new_dict)
|
updating a nested dictionary getting ReferenceError: weakly-referenced object no longer exists
|
I am connecting to my mongodb using pymongo and trying to append to a nested dictionary using the code:
myquery = User.objects.filter(username=current_user)
my_dict = myquery[0]['spare_2']
my_dict[quiz_id] = {'question1': 9, 'question2': 9, 'question3': 9, 'question4': 9, 'question5': 9, 'question6': 9, 'question7': 9, 'question8': 9, 'question9': 9, 'question10': 9}
User.objects(username=current_user).update(spare_2=my_dict)
I am getting the error:
How can I solve this? I'm a home coding enthusiast so not very knowledgeable on why this is happening, thanks
|
[
"I changed the way I was updating the dictionary and it solved the problem:\nmyquery = User.objects.filter(username=current_user)\nmy_dict = myquery[0]['spare_2']\nappend_dict = {quiz_id: 9, 'question2': 9, 'question3': 9, 'question4': 9, 'question5': 9, 'question6': 9, 'question7': 9, 'question8': 9, 'question9': 9, 'question10': 9}\nnew_dict = my_dict | append_dict\nUser.objects(username=current_user).update(spare_2=new_dict)\n\n"
] |
[
0
] |
[] |
[] |
[
"mongodb",
"pymongo",
"python"
] |
stackoverflow_0074581184_mongodb_pymongo_python.txt
|
Q:
how do i print the 2d list as an even table?
#Create a program that allows 2 players to throw a 6 sided dice and record the roll value 10 times.
#The winner is the player with the highest total
#This task must store the results in a 2D array
#Extra:
#Work out the average roll across the 10 throws per player and display the result
#Frequency analysis broken down per player and per game
from random import randint
results = [[],[]]
for i in range (2):
player = []
total = 0
average = 0
#player enters their name
name = input(f"\nEnter your name player {i + 1}: ")
player.append(name)
print(f"Player {i + 1} it is your turn")
for x in range(10):
print("\nTo roll the die press any key")
input()
roll = randint(1,6)
player.append(roll)
print("You rolled a", roll)
total += roll
average = total/10
player.append(total)
player.append(average)
results.append(player)
print("""\nNAME R1 R2 R3 R4 R5 R6 R7 R8 R9 R10 TOTAL AVG""")
for i in results:
for c in i:
print(c,end = " ")
print()
im not sure how to evenly space out the values so they are in line when they are printed.
i tried adding spaces inbetween the values when printing but if one of the names or numbers are a different length then the whole row becomes unaligned with the column.
A:
You can use the following sintax:
print('%5s' % str(c))
Basically:
the % character informs python it will have to substitute something
to a token
the s character informs python the token will be a string
the 5 (or whatever number you wish) informs python to pad the string
with spaces up to 5 characters.
I found that on How to print a string at a fixed width?.
|
how do i print the 2d list as an even table?
|
#Create a program that allows 2 players to throw a 6 sided dice and record the roll value 10 times.
#The winner is the player with the highest total
#This task must store the results in a 2D array
#Extra:
#Work out the average roll across the 10 throws per player and display the result
#Frequency analysis broken down per player and per game
from random import randint
results = [[],[]]
for i in range (2):
player = []
total = 0
average = 0
#player enters their name
name = input(f"\nEnter your name player {i + 1}: ")
player.append(name)
print(f"Player {i + 1} it is your turn")
for x in range(10):
print("\nTo roll the die press any key")
input()
roll = randint(1,6)
player.append(roll)
print("You rolled a", roll)
total += roll
average = total/10
player.append(total)
player.append(average)
results.append(player)
print("""\nNAME R1 R2 R3 R4 R5 R6 R7 R8 R9 R10 TOTAL AVG""")
for i in results:
for c in i:
print(c,end = " ")
print()
im not sure how to evenly space out the values so they are in line when they are printed.
i tried adding spaces inbetween the values when printing but if one of the names or numbers are a different length then the whole row becomes unaligned with the column.
|
[
"You can use the following sintax:\nprint('%5s' % str(c))\n\nBasically:\n\nthe % character informs python it will have to substitute something\nto a token\nthe s character informs python the token will be a string\nthe 5 (or whatever number you wish) informs python to pad the string\nwith spaces up to 5 characters.\n\nI found that on How to print a string at a fixed width?.\n"
] |
[
1
] |
[
"to calculate difference between 2 names\ndiff = abs(len(results[2][0]) - len(results[3][0])) #abs = absolute value\n\ncompare 2 lengths of names:\nif len(results[2][0] ) > len(results[3][0]):\n results[3][0] = results[3][0] + \" \"*diff # add spaces much as difference between 2 names\nelse:\n results[2][0] = results[2][0] + \" \"*diff\n\n"
] |
[
-1
] |
[
"arrays",
"list",
"multidimensional_array",
"python"
] |
stackoverflow_0074582309_arrays_list_multidimensional_array_python.txt
|
Q:
How to start a maximum of X threads ? Python
Hello i have the following question:
My goal is to submit an email to an online list. The way that I have it right now starts as many threads as emails in my 01.csv file but i want it to have a maximum of 10 threads and once 1 thread is done continue with the next one but never goes above 10 active threads.
This is my main function which gets the emails from csv and start the target function:
def main():
get_emails()
log("Starting tasks", "yellow")
# Loop through users
for user in users:
# Start thread for each user
# Random timer so everyone doesn't request at the same time
#timer = random.randint(0, 100)/100
#time.sleep(timer)
thread = threading.Thread(target=targetfunc, args=(users[user], ))
thread.start()
#os.system("clear")
log("Task started successfully!", "success")
This is the function to get the mails :
def get_emails():
global users
with open("./emails.csv", "r") as f:
data = csv.reader(f)
for i, d in enumerate(data):
if i == 0:
data_titles = d
else:
users[d[0]] = {}
for title in data_titles:
users[d[0]][title] = d[data_titles.index(title)]
And here is the targetfunc the one thats does the email submit:
def targetfunc(data):
global users_done
global successCount
#session = requests.session()
email = data["EMAIL"]
...
...
...
How would i turn this code into one that only runs 5 threads at a time?
A:
You can either implement your own queue and have 10 threads started, that each pull from the queue, or - for this simple task - you could also use a ThreadPoolExecutor with a given number of workers.
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=10) as ex:
for user in users:
ex.submit(targetfunc, (users[user], ))
|
How to start a maximum of X threads ? Python
|
Hello i have the following question:
My goal is to submit an email to an online list. The way that I have it right now starts as many threads as emails in my 01.csv file but i want it to have a maximum of 10 threads and once 1 thread is done continue with the next one but never goes above 10 active threads.
This is my main function which gets the emails from csv and start the target function:
def main():
get_emails()
log("Starting tasks", "yellow")
# Loop through users
for user in users:
# Start thread for each user
# Random timer so everyone doesn't request at the same time
#timer = random.randint(0, 100)/100
#time.sleep(timer)
thread = threading.Thread(target=targetfunc, args=(users[user], ))
thread.start()
#os.system("clear")
log("Task started successfully!", "success")
This is the function to get the mails :
def get_emails():
global users
with open("./emails.csv", "r") as f:
data = csv.reader(f)
for i, d in enumerate(data):
if i == 0:
data_titles = d
else:
users[d[0]] = {}
for title in data_titles:
users[d[0]][title] = d[data_titles.index(title)]
And here is the targetfunc the one thats does the email submit:
def targetfunc(data):
global users_done
global successCount
#session = requests.session()
email = data["EMAIL"]
...
...
...
How would i turn this code into one that only runs 5 threads at a time?
|
[
"You can either implement your own queue and have 10 threads started, that each pull from the queue, or - for this simple task - you could also use a ThreadPoolExecutor with a given number of workers.\nfrom concurrent.futures import ThreadPoolExecutor\n\nwith ThreadPoolExecutor(max_workers=10) as ex:\n for user in users:\n ex.submit(targetfunc, (users[user], ))\n\n"
] |
[
0
] |
[] |
[] |
[
"multithreading",
"python",
"python_3.x",
"python_multithreading"
] |
stackoverflow_0074581847_multithreading_python_python_3.x_python_multithreading.txt
|
Q:
Python variable scoping in nested function calls
I come to this code in a LeetCode problem
class Solution:
def maxProduct(self, root):
self.res = total = 0
def s(root):
if not root: return 0
left, right = s(root.left), s(root.right)
self.res = max(self.res, left * (total - left), right * (total - right))
return left + right + root.val
total = s(root)
s(root)
return self.res % (10**9 + 7)
I change self.res to res like the following
class Solution:
def maxProduct(self, root):
res = total = 0
def s(root):
if not root: return 0
left, right = s(root.left), s(root.right)
res = max(res, left * (total - left), right * (total - right))
return left + right + root.val
total = s(root)
s(root)
return res % (10**9 + 7)
and the code breaks with UnboundLocalError: local variable 'res' referenced before assignment. Why res has to be initialized as self.res while total does not?
A:
The problem is that the nested function s has it's own variable scope.
While it can read variables (like res) from the enclosing scope (maxProduct),
any assignment (e.g. res = max(...))
will introduce a variable in the scope of s, instead of
writing to the outer (res).
Because in this case maxProduct wants to read the modified version of res
that s produced, the trick of adding a member variable to self is used.
(In that case, s only reads the reference to self, and then adds a member, avoiding the scope issue).
See this little example for demonstration:
def foo():
def bar():
x=2
x=1
bar()
return x
foo() returns 1, not 2, because, the assignment to x in bar introduces a new variable in the scope of bar
A:
Why res has to be initialized as self.res while total does not?
It does not, but because of the rules of Python's implicit declarations, by default assignment is declaration.
Since s only reads from total, it necessarily has to come from somewhere else, but because of
res = max(self.res, left * (total - left), right * (total - right))
Python will create a res variable which is local to s, so you really have two different variables with the same name, one in maxProduct and one in s. This is called shadowing.
You can tell Python that a variable being assigned to is not a local by explicitly declaring it so:
nonlocal res
This will make Python assign to the lexically closest variable of that name:
def foo():
a = 1
def bar():
a = 2
bar()
print(a)
foo()
# 1
def foo():
a = 1
def bar():
nonlocal a
a = 2
bar()
print(a)
foo()
# 2
|
Python variable scoping in nested function calls
|
I come to this code in a LeetCode problem
class Solution:
def maxProduct(self, root):
self.res = total = 0
def s(root):
if not root: return 0
left, right = s(root.left), s(root.right)
self.res = max(self.res, left * (total - left), right * (total - right))
return left + right + root.val
total = s(root)
s(root)
return self.res % (10**9 + 7)
I change self.res to res like the following
class Solution:
def maxProduct(self, root):
res = total = 0
def s(root):
if not root: return 0
left, right = s(root.left), s(root.right)
res = max(res, left * (total - left), right * (total - right))
return left + right + root.val
total = s(root)
s(root)
return res % (10**9 + 7)
and the code breaks with UnboundLocalError: local variable 'res' referenced before assignment. Why res has to be initialized as self.res while total does not?
|
[
"The problem is that the nested function s has it's own variable scope.\nWhile it can read variables (like res) from the enclosing scope (maxProduct),\nany assignment (e.g. res = max(...))\nwill introduce a variable in the scope of s, instead of\nwriting to the outer (res).\nBecause in this case maxProduct wants to read the modified version of res\nthat s produced, the trick of adding a member variable to self is used.\n(In that case, s only reads the reference to self, and then adds a member, avoiding the scope issue).\nSee this little example for demonstration:\ndef foo():\n def bar():\n x=2\n x=1\n bar()\n return x\n\nfoo() returns 1, not 2, because, the assignment to x in bar introduces a new variable in the scope of bar\n",
"\nWhy res has to be initialized as self.res while total does not?\n\nIt does not, but because of the rules of Python's implicit declarations, by default assignment is declaration.\nSince s only reads from total, it necessarily has to come from somewhere else, but because of\n res = max(self.res, left * (total - left), right * (total - right))\n\nPython will create a res variable which is local to s, so you really have two different variables with the same name, one in maxProduct and one in s. This is called shadowing.\nYou can tell Python that a variable being assigned to is not a local by explicitly declaring it so:\nnonlocal res\n\nThis will make Python assign to the lexically closest variable of that name:\ndef foo():\n a = 1\n def bar():\n a = 2\n bar()\n print(a)\n\nfoo()\n# 1\n\ndef foo():\n a = 1\n def bar():\n nonlocal a\n a = 2\n bar()\n print(a)\n\nfoo()\n# 2\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"python",
"scope",
"variables"
] |
stackoverflow_0074582432_python_scope_variables.txt
|
Q:
Jump to another message via a button and assign another role at the same time
I have a problem. I have created a button that lets a user jump to another message in another text channel.
The user has Role1 as soon as he presses the button he should get the role Role2 and jump to the textchannel which is only enabled for Role2.
Unfortunately this does not work because the following error occurs discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'property' object has no attribute 'get_role'
How can I make a user jump to another message and give him a new role?
class Google(discord.ui.View):
def __init__(self, interaction):
super().__init__()
# we need to quote the query string to make a valid url. Discord will raise an error if it isn't valid.
url = f'https://discord.com/channels/<id>'
# Link buttons cannot be made with the decorator
# Therefore we have to manually create one.
# We add the quoted url to the button, and add the button to the view.
role = interaction.guild.get_role(<id>)
interaction.user.add_roles(role)
self.add_item(discord.ui.Button(label='Click Here', url=url))
@bot.command()
async def google(ctx: commands.Context,):
"""Returns a google link for a query"""
await ctx.send(f'Google Result for', view=Google(discord.Interaction))
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 178, in wrapped
ret = await coro(*args, **kwargs)
File "D:\Implementierung\My_first_app\discord\main.py", line 246, in google
await ctx.send(f'Google Result for', view=Google(discord.Interaction))
File "D:\Implementierung\My_first_app\discord\main.py", line 239, in __init__
role = interaction.guild.get_role(<id>)
AttributeError: 'property' object has no attribute 'get_role'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 950, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 187, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'property' object has no attribute 'get_role'
A:
As I mentioned in the comments, you are passing a class object to your view not an interaction object. And since add_roles is a coroutine you can't await it in __init__ so you better do it in the command itself instead. Hence, your view doesn't even need the interaction object.
class Google(discord.ui.View):
def __init__(self):
super().__init__()
# we need to quote the query string to make a valid url. Discord will raise an error if it isn't valid.
url = f"https://discord.com/channels/<id>"
# Link buttons cannot be made with the decorator
# Therefore we have to manually create one.
# We add the quoted url to the button, and add the button to the view.
self.add_item(discord.ui.Button(label="Click Here", url=url))
@bot.tree.command(name="google", guild=None)
async def google(interaction: discord.Interaction):
"""Returns a google link for a query"""
role = interaction.guild.get_role(<id>)
await interaction.user.add_roles(role)
await interaction.response.send_message(
f"Google Result for", view=Google() # If for some reason you need the interaction in your view you can pass it as an argument.
)
As for how to make it a slash command instead of a text command, you need to set it as a command in the bot's command tree (bot.tree.command()).
To register your slash command to discord you need owner only a sync command. Mine is like this:
@bot.command()
@commands.is_owner()
async def sync(
ctx: commands.Context[Bot],
guilds: commands.Greedy[discord.Object],
spec: Optional[Literal["~"]],
) -> None:
if not guilds:
if spec == "~":
fmt: List[AppCommand] = await ctx.bot.tree.sync(guild=ctx.guild)
else:
fmt: List[AppCommand] = await ctx.bot.tree.sync()
await ctx.send(
f"Synced {len(fmt)} commands {'globally' if spec is None else 'to the current guild.'}"
)
return
fmt_i: int = 0
for guild in guilds:
try:
await ctx.bot.tree.sync(guild=guild)
except discord.HTTPException:
pass
else:
fmt_i += 1
await ctx.send(f"Synced the tree to {fmt_i}/{len(guilds)} guilds.")
Run your code and use the <prefix>sync (with no arguments to sync as global) command to sync your slash commands, then you can use it.
|
Jump to another message via a button and assign another role at the same time
|
I have a problem. I have created a button that lets a user jump to another message in another text channel.
The user has Role1 as soon as he presses the button he should get the role Role2 and jump to the textchannel which is only enabled for Role2.
Unfortunately this does not work because the following error occurs discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'property' object has no attribute 'get_role'
How can I make a user jump to another message and give him a new role?
class Google(discord.ui.View):
def __init__(self, interaction):
super().__init__()
# we need to quote the query string to make a valid url. Discord will raise an error if it isn't valid.
url = f'https://discord.com/channels/<id>'
# Link buttons cannot be made with the decorator
# Therefore we have to manually create one.
# We add the quoted url to the button, and add the button to the view.
role = interaction.guild.get_role(<id>)
interaction.user.add_roles(role)
self.add_item(discord.ui.Button(label='Click Here', url=url))
@bot.command()
async def google(ctx: commands.Context,):
"""Returns a google link for a query"""
await ctx.send(f'Google Result for', view=Google(discord.Interaction))
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 178, in wrapped
ret = await coro(*args, **kwargs)
File "D:\Implementierung\My_first_app\discord\main.py", line 246, in google
await ctx.send(f'Google Result for', view=Google(discord.Interaction))
File "D:\Implementierung\My_first_app\discord\main.py", line 239, in __init__
role = interaction.guild.get_role(<id>)
AttributeError: 'property' object has no attribute 'get_role'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 950, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 187, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'property' object has no attribute 'get_role'
|
[
"As I mentioned in the comments, you are passing a class object to your view not an interaction object. And since add_roles is a coroutine you can't await it in __init__ so you better do it in the command itself instead. Hence, your view doesn't even need the interaction object.\nclass Google(discord.ui.View):\n def __init__(self):\n super().__init__()\n # we need to quote the query string to make a valid url. Discord will raise an error if it isn't valid.\n url = f\"https://discord.com/channels/<id>\"\n\n # Link buttons cannot be made with the decorator\n # Therefore we have to manually create one.\n # We add the quoted url to the button, and add the button to the view.\n self.add_item(discord.ui.Button(label=\"Click Here\", url=url))\n\n\n@bot.tree.command(name=\"google\", guild=None)\nasync def google(interaction: discord.Interaction):\n \"\"\"Returns a google link for a query\"\"\"\n role = interaction.guild.get_role(<id>)\n await interaction.user.add_roles(role)\n await interaction.response.send_message(\n f\"Google Result for\", view=Google() # If for some reason you need the interaction in your view you can pass it as an argument.\n )\n\nAs for how to make it a slash command instead of a text command, you need to set it as a command in the bot's command tree (bot.tree.command()).\nTo register your slash command to discord you need owner only a sync command. Mine is like this:\n@bot.command()\n@commands.is_owner()\nasync def sync(\n ctx: commands.Context[Bot],\n guilds: commands.Greedy[discord.Object],\n spec: Optional[Literal[\"~\"]],\n) -> None:\n if not guilds:\n if spec == \"~\":\n fmt: List[AppCommand] = await ctx.bot.tree.sync(guild=ctx.guild)\n else:\n fmt: List[AppCommand] = await ctx.bot.tree.sync()\n\n await ctx.send(\n f\"Synced {len(fmt)} commands {'globally' if spec is None else 'to the current guild.'}\"\n )\n return\n\n fmt_i: int = 0\n for guild in guilds:\n try:\n await ctx.bot.tree.sync(guild=guild)\n except discord.HTTPException:\n pass\n else:\n fmt_i += 1\n\n await ctx.send(f\"Synced the tree to {fmt_i}/{len(guilds)} guilds.\")\n\nRun your code and use the <prefix>sync (with no arguments to sync as global) command to sync your slash commands, then you can use it.\n"
] |
[
0
] |
[] |
[] |
[
"discord",
"discord.py",
"python",
"python_3.x"
] |
stackoverflow_0074473466_discord_discord.py_python_python_3.x.txt
|
Q:
ACCESS_TOKEN_SCOPE_INSUFFICIENT error with updating sheet using google sheets api (python)
I've been making a program in python that is intended to have each user be able to use it to access a single google sheet and read and update data on it only in the allowed ways, so ive used google api on the google developer console and managed to get test accounts reading the information that ive manually put in, however the update function returns
<HttpError 403 when requesting https://sheets.googleapis.com/v4/spreadsheets/ google sheets id here /values/write%21D1?valueInputOption=RAW&alt=json returned "Request had insufficient authentication scopes.". Details: "[{'@type': 'type.googleapis.com/google.rpc.ErrorInfo', 'reason': 'ACCESS_TOKEN_SCOPE_INSUFFICIENT', 'domain': 'googleapis.com', 'metadata': {'method': 'google.apps.sheets.v4.SpreadsheetsService.UpdateValues', 'service': 'sheets.googleapis.com'}}]">
but the scopes added and used are the ones that relate to what the program does, it has no issue with reading but refuses to update for some reason. I've deleted the token.json file and tried updating scopes but it doesn't seem to want to work.
scopes it currently has is:
non sensitive scopes:
Google Sheets API .../auth/drive.file See, edit, create and delete only the specific Google Drive files that you use with this app
sensitive scopes:
Google Sheets API .../auth/spreadsheets See, edit, create and delete all your Google Sheets spreadsheets
Google Sheets API .../auth/spreadsheets.readonly See all your Google Sheets spreadsheets
there are no restricted scopes.
code here:
from __future__ import print_function
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
# The ID and range of a sample spreadsheet.
spreadID = *redacted for security but this is the correct ID in original code*
def main():
"""Shows basic usage of the Sheets API.
Prints values from a sample spreadsheet.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
try:
service = build('sheets', 'v4', credentials=creds)
# Call the Sheets API
sheet = service.spreadsheets()
#range used for data reading
sheetdata_range = 'read!A1:E5' #"pagename!range"
result = sheet.values().get(spreadsheetId=spreadID,
range=sheetdata_range).execute()
#this is the command that gets the values from the range
values = result.get('values', [])
#print(f"""values variable is:
#{values}""")
if not values:#if nothing found it returns this.
print('No data found.')
return
for item in values[0]:#for item in row 1
print(f"values[0] test {item}")
for row in values:#prints items from col 1
print(row[0])
rangeupdate = [["1","2","3"],["a","b","c"]]
request = sheet.values().update(spreadsheetId=spreadID,
range="write!D1",#this is the start point, lists and 2d lists work from this point
valueInputOption="RAW",#how the data is added, this prevents the data being interpreted
body={"values":rangeupdate}).execute()
print(request)
except HttpError as err:
print(err)
if __name__ == '__main__':
main()
A:
You are using the sheets.values.update method. If you check the documentation. you will see that this method requires one of the following scopes of authorization
Your code apears to only request 'https://www.googleapis.com/auth/spreadsheets.readonly' read only access is not going to let you write to the file. You need to request the proper scope.
|
ACCESS_TOKEN_SCOPE_INSUFFICIENT error with updating sheet using google sheets api (python)
|
I've been making a program in python that is intended to have each user be able to use it to access a single google sheet and read and update data on it only in the allowed ways, so ive used google api on the google developer console and managed to get test accounts reading the information that ive manually put in, however the update function returns
<HttpError 403 when requesting https://sheets.googleapis.com/v4/spreadsheets/ google sheets id here /values/write%21D1?valueInputOption=RAW&alt=json returned "Request had insufficient authentication scopes.". Details: "[{'@type': 'type.googleapis.com/google.rpc.ErrorInfo', 'reason': 'ACCESS_TOKEN_SCOPE_INSUFFICIENT', 'domain': 'googleapis.com', 'metadata': {'method': 'google.apps.sheets.v4.SpreadsheetsService.UpdateValues', 'service': 'sheets.googleapis.com'}}]">
but the scopes added and used are the ones that relate to what the program does, it has no issue with reading but refuses to update for some reason. I've deleted the token.json file and tried updating scopes but it doesn't seem to want to work.
scopes it currently has is:
non sensitive scopes:
Google Sheets API .../auth/drive.file See, edit, create and delete only the specific Google Drive files that you use with this app
sensitive scopes:
Google Sheets API .../auth/spreadsheets See, edit, create and delete all your Google Sheets spreadsheets
Google Sheets API .../auth/spreadsheets.readonly See all your Google Sheets spreadsheets
there are no restricted scopes.
code here:
from __future__ import print_function
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
# The ID and range of a sample spreadsheet.
spreadID = *redacted for security but this is the correct ID in original code*
def main():
"""Shows basic usage of the Sheets API.
Prints values from a sample spreadsheet.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
try:
service = build('sheets', 'v4', credentials=creds)
# Call the Sheets API
sheet = service.spreadsheets()
#range used for data reading
sheetdata_range = 'read!A1:E5' #"pagename!range"
result = sheet.values().get(spreadsheetId=spreadID,
range=sheetdata_range).execute()
#this is the command that gets the values from the range
values = result.get('values', [])
#print(f"""values variable is:
#{values}""")
if not values:#if nothing found it returns this.
print('No data found.')
return
for item in values[0]:#for item in row 1
print(f"values[0] test {item}")
for row in values:#prints items from col 1
print(row[0])
rangeupdate = [["1","2","3"],["a","b","c"]]
request = sheet.values().update(spreadsheetId=spreadID,
range="write!D1",#this is the start point, lists and 2d lists work from this point
valueInputOption="RAW",#how the data is added, this prevents the data being interpreted
body={"values":rangeupdate}).execute()
print(request)
except HttpError as err:
print(err)
if __name__ == '__main__':
main()
|
[
"You are using the sheets.values.update method. If you check the documentation. you will see that this method requires one of the following scopes of authorization\n\nYour code apears to only request 'https://www.googleapis.com/auth/spreadsheets.readonly' read only access is not going to let you write to the file. You need to request the proper scope.\n"
] |
[
1
] |
[] |
[] |
[
"google_api_python_client",
"google_oauth",
"google_sheets",
"google_sheets_api",
"python"
] |
stackoverflow_0074582213_google_api_python_client_google_oauth_google_sheets_google_sheets_api_python.txt
|
Q:
discord.py change nickname after a modal submit
I wanted to change my modal a nickname but unfortunately do not know exactly how
this is my code
class RenameModal(ui.Modal, title="Rename"):
vorname = ui.TextInput(label="Vorname", placeholder="Mein Vorname lautet...", required=True, style=discord.TextStyle.short)
nachname = ui.TextInput(label="Nachname", placeholder="Mein Nachname lautet...", required=True, style=discord.TextStyle.short)
spielerid = ui.TextInput(label="ID", placeholder="Meine ID lautet...", required=True, style=discord.TextStyle.short)
async def on_submit(self, interaction: discord.Interaction):
await interaction.user.edit(nick=f'{self.vorname} {self.nachname} | {self.spielerid}')
@client.tree.command(name="rename", description="rename")
async def rename(interaction: discord.Interaction):
await interaction.response.send_modal(RenameModal())
as mentioned before i would like to change the nickname of the user after sending the modal
so far I have only tried that and found nothing about it
await interaction.user.edit(nick=f'{self.vorname} {self.nachname} | {self.spielerid}')
A:
Try changing
await interaction.user.edit
to
await interaction.member.edit
as user is the global term that is used for all over Discord, and member is the term used for a user in a specific Guild.
|
discord.py change nickname after a modal submit
|
I wanted to change my modal a nickname but unfortunately do not know exactly how
this is my code
class RenameModal(ui.Modal, title="Rename"):
vorname = ui.TextInput(label="Vorname", placeholder="Mein Vorname lautet...", required=True, style=discord.TextStyle.short)
nachname = ui.TextInput(label="Nachname", placeholder="Mein Nachname lautet...", required=True, style=discord.TextStyle.short)
spielerid = ui.TextInput(label="ID", placeholder="Meine ID lautet...", required=True, style=discord.TextStyle.short)
async def on_submit(self, interaction: discord.Interaction):
await interaction.user.edit(nick=f'{self.vorname} {self.nachname} | {self.spielerid}')
@client.tree.command(name="rename", description="rename")
async def rename(interaction: discord.Interaction):
await interaction.response.send_modal(RenameModal())
as mentioned before i would like to change the nickname of the user after sending the modal
so far I have only tried that and found nothing about it
await interaction.user.edit(nick=f'{self.vorname} {self.nachname} | {self.spielerid}')
|
[
"Try changing\nawait interaction.user.edit\n\nto\nawait interaction.member.edit\n\nas user is the global term that is used for all over Discord, and member is the term used for a user in a specific Guild.\n"
] |
[
0
] |
[] |
[] |
[
"discord",
"discord.py",
"discord_interactions",
"python"
] |
stackoverflow_0074571147_discord_discord.py_discord_interactions_python.txt
|
Q:
How to implement CSV Writer in a named temporary - Python?
Basically, I need final a csv file, whose contents look like Header, and then the data:
(Boto3 upload_file does the job of writing temporary file, into csv)
Expectation:
Name,Code
Adam,12
I am able to get this, by using:
with tempfile.NamedTemporaryFile(mode="a+t", suffix =".csv", delete=True) as fileName:
for data in allData:
fileName.write(data)
fileName.flush()
But, when I am using csv.writer:
writer = csv.write(fileName)
with tempfile.NamedTemporaryFile(mode="a+t", suffix =".csv", delete=True) as fileName:
for data in allData:
writer.writerow(data)
Reality:
N,a,m,e","C,o,d,e
A,d,a,m","1,2"
Using Python 3.8
allData looks like: [{'name': 'Adam', 'code': '12', 'points': 9.7, 'age': '34'}, {{'name': 'Sam', 'code': '13', 'points': 8.4, 'age': '34'}]. (There are 1000 data like this, and using a context filters out the values only.)
A data looks like: Adam,12
Need help writing this with csv writer. I have seen references of StringIO being used to fix similar cases, but do not know how to implement. Is there a way out?
A:
This doesn't have anything to do with the temporary directory.
Here is part of the introduction about CSV writer objects (bold added):
A row must be an iterable of strings or numbers for Writer objects and a dictionary mapping fieldnames to strings or numbers... for DictWriter objects
But you are passing in a single string: "Adam,12". So what's going on?
Strings themselves are iterables over the characters in the string:
>>> for character in "Adam":
... print(character)
...
A
d
a
m
And since Python doesn't have a distinct character class, each of those single-character values is also a string. So strings are iterables of strings.
When you give an iterable of strings to csvwriter.writerow(), it writes each string in the iterable to its own column. In this case, that means one-character strings taken from the input.
To get the behaviour you're after, you'll need to pass something like ["Adam", 12] (not "Adam,12") to the CSV writer. I'm not sure where your inputs are coming from, so there might be a better way to do this, but you could split your strings on the comma as you pass them in:
for data in allData:
writer.writerow(data.split(","))
This works because "Adam,12".split(",") returns ["Adam", "12"]. Note that this won't work properly if your inputs have multiple commas.
Edit:
If allData is a list of dictionaries, as you show in the edited question, you might be better off with a DictWriter instead of a regular writer:
Create an object which operates like a regular writer but maps dictionaries onto output rows. The fieldnames parameter is a sequence of keys that identify the order in which values in the dictionary passed to the writerow() method are written to file f.
In other words, something like this:
with open("foo.csv", "w") as f:
writer = csv.DictWriter(f, ["name", "code", "points", "age"])
for data in [{"name": "Adam", "code": 12, "points": 0, "age": 18}]:
writer.writerow(data)
|
How to implement CSV Writer in a named temporary - Python?
|
Basically, I need final a csv file, whose contents look like Header, and then the data:
(Boto3 upload_file does the job of writing temporary file, into csv)
Expectation:
Name,Code
Adam,12
I am able to get this, by using:
with tempfile.NamedTemporaryFile(mode="a+t", suffix =".csv", delete=True) as fileName:
for data in allData:
fileName.write(data)
fileName.flush()
But, when I am using csv.writer:
writer = csv.write(fileName)
with tempfile.NamedTemporaryFile(mode="a+t", suffix =".csv", delete=True) as fileName:
for data in allData:
writer.writerow(data)
Reality:
N,a,m,e","C,o,d,e
A,d,a,m","1,2"
Using Python 3.8
allData looks like: [{'name': 'Adam', 'code': '12', 'points': 9.7, 'age': '34'}, {{'name': 'Sam', 'code': '13', 'points': 8.4, 'age': '34'}]. (There are 1000 data like this, and using a context filters out the values only.)
A data looks like: Adam,12
Need help writing this with csv writer. I have seen references of StringIO being used to fix similar cases, but do not know how to implement. Is there a way out?
|
[
"This doesn't have anything to do with the temporary directory.\nHere is part of the introduction about CSV writer objects (bold added):\n\nA row must be an iterable of strings or numbers for Writer objects and a dictionary mapping fieldnames to strings or numbers... for DictWriter objects\n\nBut you are passing in a single string: \"Adam,12\". So what's going on?\nStrings themselves are iterables over the characters in the string:\n>>> for character in \"Adam\":\n... print(character)\n...\nA\nd\na\nm\n\nAnd since Python doesn't have a distinct character class, each of those single-character values is also a string. So strings are iterables of strings.\nWhen you give an iterable of strings to csvwriter.writerow(), it writes each string in the iterable to its own column. In this case, that means one-character strings taken from the input.\nTo get the behaviour you're after, you'll need to pass something like [\"Adam\", 12] (not \"Adam,12\") to the CSV writer. I'm not sure where your inputs are coming from, so there might be a better way to do this, but you could split your strings on the comma as you pass them in:\nfor data in allData:\n writer.writerow(data.split(\",\"))\n\nThis works because \"Adam,12\".split(\",\") returns [\"Adam\", \"12\"]. Note that this won't work properly if your inputs have multiple commas.\nEdit:\nIf allData is a list of dictionaries, as you show in the edited question, you might be better off with a DictWriter instead of a regular writer:\n\nCreate an object which operates like a regular writer but maps dictionaries onto output rows. The fieldnames parameter is a sequence of keys that identify the order in which values in the dictionary passed to the writerow() method are written to file f.\n\nIn other words, something like this:\nwith open(\"foo.csv\", \"w\") as f:\n writer = csv.DictWriter(f, [\"name\", \"code\", \"points\", \"age\"])\n for data in [{\"name\": \"Adam\", \"code\": 12, \"points\": 0, \"age\": 18}]:\n writer.writerow(data)\n\n"
] |
[
2
] |
[] |
[] |
[
"airflow",
"csv",
"python",
"python_3.x"
] |
stackoverflow_0074582234_airflow_csv_python_python_3.x.txt
|
Q:
Convert parquet to list of objects in python
I am reading a parquet file with panda:
import pandas as pd
df = pd.read_parquet('myfile.parquet', engine='pyarrow')
The file has the following structure:
company_id
user_id
attribute_name
attribute_value
timestamp
1
116664
111f07000612
first_name
Tom
2022-03-23 17:11:58
2
116664
111f07000612
last_name
Cruise
2022-03-23 17:11:58
3
116664
111f07000612
city
New York
2022-03-23 17:11:58
4
116664
abcf0700d009d122
first_name
Matt
2022-02-23 10:11:59
5
116664
abcf0700d009d122
last_name
Damon
2022-02-23 10:11:59
I would like to group by user_id and generate a list of objects (that will be stored as json) with the following format:
[
{
"user_id": "111f07000612",
"first_name": "Tom",
"last_name": "Cruise",
"city": "New York"
},
{
"user_id": "abcf0700d009d122",
"first_name": "Matt",
"last_name": "Damon"
}
]
A:
Hi Hope you are doing well!
You can achieve it with something similar to this
from pprint import pprint
import pandas as pd
# because I don't have the exact parquet file, I will just mock it
# df = pd.read_parquet("myfile.parquet", engine="pyarrow")
df = pd.DataFrame(
{
"company_id": [116664, 116664, 116664, 116664, 116664],
"user_id": ["111f07000612", "111f07000612", "111f07000612", "abcf0700d009d122", "abcf0700d009d122"],
"attribute_name": ["first_name", "last_name", "city", "first_name", "last_name"],
"attribute_value": ["Tom", "Cruise", "New York", "Matt", "Damon"],
"timestamp": ["2022-03-23 17:11:58", "2022-03-23 17:11:58", "2022-03-23 17:11:58", "2022-03-23 17:11:58", "2022-03-23 17:11:58"]
}
)
records = []
for user_id, group in df.groupby("user_id"):
transformed_group = (
group[["attribute_name", "attribute_value"]]
.set_index("attribute_name")
.transpose()
.assign(user_id=user_id)
)
rercord, *_ = transformed_group.to_dict("records")
records.append(rercord)
pprint(records)
# [{'city': 'New York',
# 'first_name': 'Tom',
# 'last_name': 'Cruise',
# 'user_id': '111f07000612'},
# {'first_name': 'Matt', 'last_name': 'Damon', 'user_id': 'abcf0700d009d122'}]
|
Convert parquet to list of objects in python
|
I am reading a parquet file with panda:
import pandas as pd
df = pd.read_parquet('myfile.parquet', engine='pyarrow')
The file has the following structure:
company_id
user_id
attribute_name
attribute_value
timestamp
1
116664
111f07000612
first_name
Tom
2022-03-23 17:11:58
2
116664
111f07000612
last_name
Cruise
2022-03-23 17:11:58
3
116664
111f07000612
city
New York
2022-03-23 17:11:58
4
116664
abcf0700d009d122
first_name
Matt
2022-02-23 10:11:59
5
116664
abcf0700d009d122
last_name
Damon
2022-02-23 10:11:59
I would like to group by user_id and generate a list of objects (that will be stored as json) with the following format:
[
{
"user_id": "111f07000612",
"first_name": "Tom",
"last_name": "Cruise",
"city": "New York"
},
{
"user_id": "abcf0700d009d122",
"first_name": "Matt",
"last_name": "Damon"
}
]
|
[
"Hi Hope you are doing well!\nYou can achieve it with something similar to this \n\nfrom pprint import pprint\n\nimport pandas as pd\n\n\n# because I don't have the exact parquet file, I will just mock it\n# df = pd.read_parquet(\"myfile.parquet\", engine=\"pyarrow\")\ndf = pd.DataFrame(\n {\n \"company_id\": [116664, 116664, 116664, 116664, 116664],\n \"user_id\": [\"111f07000612\", \"111f07000612\", \"111f07000612\", \"abcf0700d009d122\", \"abcf0700d009d122\"],\n \"attribute_name\": [\"first_name\", \"last_name\", \"city\", \"first_name\", \"last_name\"],\n \"attribute_value\": [\"Tom\", \"Cruise\", \"New York\", \"Matt\", \"Damon\"],\n \"timestamp\": [\"2022-03-23 17:11:58\", \"2022-03-23 17:11:58\", \"2022-03-23 17:11:58\", \"2022-03-23 17:11:58\", \"2022-03-23 17:11:58\"]\n }\n)\n\nrecords = []\n\nfor user_id, group in df.groupby(\"user_id\"):\n transformed_group = (\n group[[\"attribute_name\", \"attribute_value\"]]\n .set_index(\"attribute_name\")\n .transpose()\n .assign(user_id=user_id)\n )\n rercord, *_ = transformed_group.to_dict(\"records\")\n records.append(rercord)\n\npprint(records)\n# [{'city': 'New York',\n# 'first_name': 'Tom',\n# 'last_name': 'Cruise',\n# 'user_id': '111f07000612'},\n# {'first_name': 'Matt', 'last_name': 'Damon', 'user_id': 'abcf0700d009d122'}]\n\n"
] |
[
0
] |
[] |
[] |
[
"pandas",
"parquet",
"python"
] |
stackoverflow_0074563600_pandas_parquet_python.txt
|
Q:
what will happen if we pass an argument to a C++ recursive function like "pass_by_keyword" in python?
int dfs(int idx, int mv, char gest){
if (idx > n || mv > k){
return 0;
}
int tmp1 = 0;
if(mv<k){
if(fj[idx]=='H'){
if(gest!='P'){
tmp1=1+dfs(idx+1,mv+1, gest='P');
}
else{
tmp1=1+dfs(idx+1, mv, gest='P');
}
}
else if(fj[idx]=='P'){
if(gest!='S'){
tmp1=1+dfs(idx+1,mv+1, 'S');
}
else{
tmp1=1+dfs(idx+1, mv, 'S');
}
}
else if(fj[idx]=='S'){
if(gest!='H'){
tmp1=1+dfs(idx+1,mv+1,'H');
}
else{
tmp1=1+dfs(idx+1, mv, 'H');
}
}
}
int tmp2 = 0;
if (check(fj[idx], gest)){
tmp2 = 1 + dfs(idx + 1, mv, gest);
}
else{
tmp2 = dfs(idx + 1, mv, gest);
}
return max(tmp1, tmp2);
}
In order to complete an OI problem, I wrote the previous dfs function, but lines 9 and 12 led to incorrect results. If I delete the "gest=" in front of the parameter, the result is correct. Why? What problems will such function parameter transfer bring in C++?
if(mv<k){
if(fj[idx]=='H'){
if(gest!='P'){
tmp1=1+dfs(idx+1,mv+1, 'P');
}
else{
tmp1=1+dfs(idx+1, mv, 'P');
}
}
else if(fj[idx]=='P'){
if(gest!='S'){
tmp1=1+dfs(idx+1,mv+1, 'S');
}
else{
tmp1=1+dfs(idx+1, mv, 'S');
}
}
else if(fj[idx]=='S'){
if(gest!='H'){
tmp1=1+dfs(idx+1,mv+1,'H');
}
else{
tmp1=1+dfs(idx+1, mv, 'H');
}
}
}
this is right.
A:
C++ does not support named parameters. What you are doing is equivalent to this:
gest='P';
tmp1=1+dfs(idx+1,mv+1, gest);
|
what will happen if we pass an argument to a C++ recursive function like "pass_by_keyword" in python?
|
int dfs(int idx, int mv, char gest){
if (idx > n || mv > k){
return 0;
}
int tmp1 = 0;
if(mv<k){
if(fj[idx]=='H'){
if(gest!='P'){
tmp1=1+dfs(idx+1,mv+1, gest='P');
}
else{
tmp1=1+dfs(idx+1, mv, gest='P');
}
}
else if(fj[idx]=='P'){
if(gest!='S'){
tmp1=1+dfs(idx+1,mv+1, 'S');
}
else{
tmp1=1+dfs(idx+1, mv, 'S');
}
}
else if(fj[idx]=='S'){
if(gest!='H'){
tmp1=1+dfs(idx+1,mv+1,'H');
}
else{
tmp1=1+dfs(idx+1, mv, 'H');
}
}
}
int tmp2 = 0;
if (check(fj[idx], gest)){
tmp2 = 1 + dfs(idx + 1, mv, gest);
}
else{
tmp2 = dfs(idx + 1, mv, gest);
}
return max(tmp1, tmp2);
}
In order to complete an OI problem, I wrote the previous dfs function, but lines 9 and 12 led to incorrect results. If I delete the "gest=" in front of the parameter, the result is correct. Why? What problems will such function parameter transfer bring in C++?
if(mv<k){
if(fj[idx]=='H'){
if(gest!='P'){
tmp1=1+dfs(idx+1,mv+1, 'P');
}
else{
tmp1=1+dfs(idx+1, mv, 'P');
}
}
else if(fj[idx]=='P'){
if(gest!='S'){
tmp1=1+dfs(idx+1,mv+1, 'S');
}
else{
tmp1=1+dfs(idx+1, mv, 'S');
}
}
else if(fj[idx]=='S'){
if(gest!='H'){
tmp1=1+dfs(idx+1,mv+1,'H');
}
else{
tmp1=1+dfs(idx+1, mv, 'H');
}
}
}
this is right.
|
[
"C++ does not support named parameters. What you are doing is equivalent to this:\ngest='P';\ntmp1=1+dfs(idx+1,mv+1, gest);\n\n"
] |
[
1
] |
[
"In C++ you cannot specify the names of the parameters to use a value for when calling a function the way it's possible in python.\ndfs(idx+1,mv+1, gest='P')\n\nwill overwrite the value of the gest parameter with 'P' and then evaluate to the new value, so after this expression gest has a different value.\nI.e. the following 2 snippets have the same effect:\ntmp1=1+dfs(idx+1,mv+1, gest='P');\n\ngest = 'P';\ntmp1=1+dfs(idx+1,mv+1, gest);\n\n"
] |
[
-1
] |
[
"c++",
"python"
] |
stackoverflow_0074582565_c++_python.txt
|
Q:
Reading csv file with no column names python
Hi I wanted to ask that i got a data of 80 columns and all of them have no names and its 80 columns and 12500 rows long and there are blank columns between them
8,1,,0,1993,146,,2,1,,,,,,,,,,2.1,0.65,0.15,0.65,19.1,,18.03,,,19.6,,,0.06,,,,,,19.1,19.6294717,19.36473585,0.06,,,,51.25,19.3,23.3,-0.04,-0.04,0.34,0.07,0.16,,,0.16,,,,,,,,,,,,,,,,,,15.3,7.8,11.55,58,100,79,15.4,8,11.7
I want to use this csv file and i want to delete the extra blank columns which i might do from using the code line
data = data.dropna()
bur it only can delete the rows i think further more how can I access or name the particular column
data = pd.read_csv('CollectedData.csv')
A:
IIUC, use this pandas.read_csv with header=None and pandas.DataFrame.dropna on axis=1:
data = pd.read_csv("CollectedData.csv", header=None).dropna(axis=1, how="all")
If you need to give names to each column, use names parameter:
cols_names= ["ColA", "ColB", "ColC", ..]
data = (
pd.read_csv("CollectedData.csv",
header=None,
names=cols_names)
.dropna(axis=1, how="all")
)
|
Reading csv file with no column names python
|
Hi I wanted to ask that i got a data of 80 columns and all of them have no names and its 80 columns and 12500 rows long and there are blank columns between them
8,1,,0,1993,146,,2,1,,,,,,,,,,2.1,0.65,0.15,0.65,19.1,,18.03,,,19.6,,,0.06,,,,,,19.1,19.6294717,19.36473585,0.06,,,,51.25,19.3,23.3,-0.04,-0.04,0.34,0.07,0.16,,,0.16,,,,,,,,,,,,,,,,,,15.3,7.8,11.55,58,100,79,15.4,8,11.7
I want to use this csv file and i want to delete the extra blank columns which i might do from using the code line
data = data.dropna()
bur it only can delete the rows i think further more how can I access or name the particular column
data = pd.read_csv('CollectedData.csv')
|
[
"IIUC, use this pandas.read_csv with header=None and pandas.DataFrame.dropna on axis=1:\ndata = pd.read_csv(\"CollectedData.csv\", header=None).dropna(axis=1, how=\"all\")\n\nIf you need to give names to each column, use names parameter:\ncols_names= [\"ColA\", \"ColB\", \"ColC\", ..]\n\ndata = (\n pd.read_csv(\"CollectedData.csv\",\n header=None,\n names=cols_names)\n .dropna(axis=1, how=\"all\")\n )\n\n"
] |
[
0
] |
[] |
[] |
[
"dataframe",
"pandas",
"python"
] |
stackoverflow_0074582725_dataframe_pandas_python.txt
|
Q:
how to run two activities at the same time in python
i want to make two lists from the same source of html data but i want to collect the data at the same time so as to avoid a possible change in the data.
this is the code i have:
lok = []
num = 6
for _ in range(num):
inner = driver.find_element_by_xpath(
"/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]").get_attribute(
"innerHTML")
lok.append(inner)
time.sleep(3600)
print(lok)
lokk = []
nums = 7
for _ in range(nums):
inner = driver.find_element_by_xpath(
"/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]").get_attribute(
"innerHTML")
lokk.append(inner)
time.sleep(3600)
print(lokk)
this code collects this data:
lok = ['1', '2', '3', '4', '5', '6']
lokk = ['7', '8', '9', '10', '11', '12', '13']
my problem however is that by the time lokk is being collected the time has changed and the values have changed as well. What i want to happen is this:
lok = ['1', '2', '3', '4', '5', '6']
lokk = ['1', '2', '3', '4', '5', '6', '7']
A:
You can append to lokk at the same time as lok and then only collect one more value in the second loop
lok = []
num = 6
for _ in range(num):
inner = driver.find_element_by_xpath(
"/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]").get_attribute(
"innerHTML")
lok.append(inner)
lokk.append(inner) # also append to lokk
time.sleep(3600)
print(lok)
lokk = []
nums = 1 # only collect 1 more piece of data
for _ in range(nums):
inner = driver.find_element_by_xpath(
"/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]").get_attribute(
"innerHTML")
lokk.append(inner)
time.sleep(3600)
print(lokk)
|
how to run two activities at the same time in python
|
i want to make two lists from the same source of html data but i want to collect the data at the same time so as to avoid a possible change in the data.
this is the code i have:
lok = []
num = 6
for _ in range(num):
inner = driver.find_element_by_xpath(
"/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]").get_attribute(
"innerHTML")
lok.append(inner)
time.sleep(3600)
print(lok)
lokk = []
nums = 7
for _ in range(nums):
inner = driver.find_element_by_xpath(
"/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]").get_attribute(
"innerHTML")
lokk.append(inner)
time.sleep(3600)
print(lokk)
this code collects this data:
lok = ['1', '2', '3', '4', '5', '6']
lokk = ['7', '8', '9', '10', '11', '12', '13']
my problem however is that by the time lokk is being collected the time has changed and the values have changed as well. What i want to happen is this:
lok = ['1', '2', '3', '4', '5', '6']
lokk = ['1', '2', '3', '4', '5', '6', '7']
|
[
"You can append to lokk at the same time as lok and then only collect one more value in the second loop\nlok = []\nnum = 6\nfor _ in range(num):\n inner = driver.find_element_by_xpath(\n \"/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]\").get_attribute(\n \"innerHTML\")\n lok.append(inner)\n lokk.append(inner) # also append to lokk\n time.sleep(3600)\n print(lok)\n\n\nlokk = []\nnums = 1 # only collect 1 more piece of data\nfor _ in range(nums):\n inner = driver.find_element_by_xpath(\n \"/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]\").get_attribute(\n \"innerHTML\")\n lokk.append(inner)\n time.sleep(3600)\n print(lokk)\n\n\n"
] |
[
0
] |
[] |
[] |
[
"html",
"list",
"python"
] |
stackoverflow_0074582700_html_list_python.txt
|
Q:
How do I make Selenium Driver in Python wait until .get() page loads fully to get entire page source?
My Selenium Driver is suddenly receiving None when requesting from a page. I want to store urlx inside dictionary data but my driver.get(x) is returning None.
self.data= {
"google.com": page_source,
"stackoverflow.com/....": page_source,
etc...
}
I tried using
self.data[link] = self.driver.get(link)
try:
self.data[link] = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located(By.NAME, "?"))
finally:
continue
but it doesnt seem to stop and wait, also I don't want to wait for a specific element, I want for the entire page to finish loading.
I've also tried to use driver.implicity_wait(10) but it doesnt seem to wait at all.
How do I do this?
A:
Reference this answer to the above question.
driver.get("https://stackoverflow.com")
pageSource = driver.page_source
fileToWrite = open("page_source.html", "w")
fileToWrite.write(pageSource)
fileToWrite.close()
fileToRead = open("page_source.html", "r")
print(fileToRead.read())
fileToRead.close()
driver.quit()
|
How do I make Selenium Driver in Python wait until .get() page loads fully to get entire page source?
|
My Selenium Driver is suddenly receiving None when requesting from a page. I want to store urlx inside dictionary data but my driver.get(x) is returning None.
self.data= {
"google.com": page_source,
"stackoverflow.com/....": page_source,
etc...
}
I tried using
self.data[link] = self.driver.get(link)
try:
self.data[link] = WebDriverWait(self.driver, 10).until(EC.presence_of_element_located(By.NAME, "?"))
finally:
continue
but it doesnt seem to stop and wait, also I don't want to wait for a specific element, I want for the entire page to finish loading.
I've also tried to use driver.implicity_wait(10) but it doesnt seem to wait at all.
How do I do this?
|
[
"Reference this answer to the above question.\ndriver.get(\"https://stackoverflow.com\")\npageSource = driver.page_source\nfileToWrite = open(\"page_source.html\", \"w\")\nfileToWrite.write(pageSource)\nfileToWrite.close()\nfileToRead = open(\"page_source.html\", \"r\")\nprint(fileToRead.read())\nfileToRead.close()\ndriver.quit()\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"selenium"
] |
stackoverflow_0074581921_python_selenium.txt
|
Q:
Pygame: update in the while loop not succesful
A helicopter is shot at. If he is hit, he falls. At the same time, a parachute releases from the helicopter. If the parachute is shot at and also hit by a bullet, the image of the parachute should be replaced with another image.
The jump with the parachute is done by the function absprung. The parachute is created with the Fallschirm class. The shelling is queried via collide.
It doesn't work, the picture is not changed.
def absprung(self): #Auslöser Fallschirm
fallschirm = Fallschirm(self.rect.centerx, self.rect.top)
alle_sprites.add(fallschirm)
fallschirme.add(fallschirm)
class Fallschirm(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("Bilder/fallschirm.png").convert_alpha()
self.image = pygame.transform.scale(self.image,(100,150))
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.beschuss = False
def update(self):
if self.beschuss == True:
self.image = pygame.image.load("Bilder/fadenkreuz.png").convert_alpha()
self.image = pygame.transform.scale(self.image,(100,150))
self.rect.y +=2
if self.rect.y > hoehe:
self.kill()
hits = pygame.sprite.groupcollide(fallschirme,bullets,False,True)
for hit in hits:
fallschirme.beschuss = True
A:
beschuss is an attribute of a single Falschirm object, but not an attribute of fallschirme. pygame.sprite.groupcollide returns a dictionary of objects that were hit. You must set the attribute to these objects.
hits = pygame.sprite.groupcollide(fallschirme, bullets,False,True)
for fallschirm in hits:
fallschirm.beschuss = True
|
Pygame: update in the while loop not succesful
|
A helicopter is shot at. If he is hit, he falls. At the same time, a parachute releases from the helicopter. If the parachute is shot at and also hit by a bullet, the image of the parachute should be replaced with another image.
The jump with the parachute is done by the function absprung. The parachute is created with the Fallschirm class. The shelling is queried via collide.
It doesn't work, the picture is not changed.
def absprung(self): #Auslöser Fallschirm
fallschirm = Fallschirm(self.rect.centerx, self.rect.top)
alle_sprites.add(fallschirm)
fallschirme.add(fallschirm)
class Fallschirm(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("Bilder/fallschirm.png").convert_alpha()
self.image = pygame.transform.scale(self.image,(100,150))
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.beschuss = False
def update(self):
if self.beschuss == True:
self.image = pygame.image.load("Bilder/fadenkreuz.png").convert_alpha()
self.image = pygame.transform.scale(self.image,(100,150))
self.rect.y +=2
if self.rect.y > hoehe:
self.kill()
hits = pygame.sprite.groupcollide(fallschirme,bullets,False,True)
for hit in hits:
fallschirme.beschuss = True
|
[
"beschuss is an attribute of a single Falschirm object, but not an attribute of fallschirme. pygame.sprite.groupcollide returns a dictionary of objects that were hit. You must set the attribute to these objects.\nhits = pygame.sprite.groupcollide(fallschirme, bullets,False,True) \nfor fallschirm in hits: \n fallschirm.beschuss = True\n\n"
] |
[
2
] |
[] |
[] |
[
"pygame",
"python"
] |
stackoverflow_0074580019_pygame_python.txt
|
Q:
Python throwing expected indented block error for no reason
My python script throwing expected indented block for no reason?
My Code
def start():
if sibr == "0x1":
ibrs = "1"
print(error)
time.sleep(0.1)
os.system("cls" if os name == "NT" else "clear")
if sibr != "0x1":
cmd()
My output
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
start(fakepyfile,mainpyfile)
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
exec(open(mainpyfile).read(), __main__.__dict__)
File "<string>", line 85
def start():
IndentationError: expected an indented block
[Program finished]
i tried to rewrite the function but not worked
|
Python throwing expected indented block error for no reason
|
My python script throwing expected indented block for no reason?
My Code
def start():
if sibr == "0x1":
ibrs = "1"
print(error)
time.sleep(0.1)
os.system("cls" if os name == "NT" else "clear")
if sibr != "0x1":
cmd()
My output
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
start(fakepyfile,mainpyfile)
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
exec(open(mainpyfile).read(), __main__.__dict__)
File "<string>", line 85
def start():
IndentationError: expected an indented block
[Program finished]
i tried to rewrite the function but not worked
|
[] |
[] |
[
"The error probably occurs above this block of code since IndetationError is already thrown for the def start(): line\n"
] |
[
-1
] |
[
"python"
] |
stackoverflow_0074582795_python.txt
|
Q:
How to find the namespace of a class easily in Python without using an IDE?
Normally, I use IntelliJ for python programming. But sometimes I don't have access to it or just to make a quick edit I open a Python file in a text editor.
At those times, it is really difficult to find the namespace of a class. I am googling it. But it takes time. Is there a better way to do this?
Edit:
Looking at the responses, I noticed that my question was not very clear.
I need to find the namespace of a class at coding time, not in runtime. Therefore, introspection methods like using inspect or __module__ doesn't help me.
WildSeal suggests using online doc. This is good but it is only useful for Python's standard libraries. I want to search all the modules installed in my current Python path. This is easy with IntelliJ. It has already indexed all the files.
I tried to use grep to search for the class inside the site-packages directory. But it takes a lot of time to search all the files, probably since they have not been indexed.
A:
Let us not forget about dir(), which is heavily used by those of us who use vim as our IDE.
A:
Try inspect.getmodule:
>>> import inspect
>>> class Foo:
pass
>>> inspect.getmodule(Foo)
<module '__main__' (built-in)>
Lots of other cool stuff in there, too.
A:
I use ctags and I've got my site-packages as well as other folders indexed in advance. There are a number of GUI and command line tools that will integrate with ctags to do what you need. Personally, I use vim as a text editor with the TagList plugin (instructions).
A:
The special attribute __module__ is the module name in which a class was defined. It will be '__main__' if defined in the top-level script.
A:
You can check the online documentation, or the documentation installed with Python. If you search for a function or class, you'll get all the relevant information (I assume you meant the package or module of a class or of a function, in the Python standard library).
There aren't so many of them though, at least that people usually use at the same time, so you should quickly get to know them.
|
How to find the namespace of a class easily in Python without using an IDE?
|
Normally, I use IntelliJ for python programming. But sometimes I don't have access to it or just to make a quick edit I open a Python file in a text editor.
At those times, it is really difficult to find the namespace of a class. I am googling it. But it takes time. Is there a better way to do this?
Edit:
Looking at the responses, I noticed that my question was not very clear.
I need to find the namespace of a class at coding time, not in runtime. Therefore, introspection methods like using inspect or __module__ doesn't help me.
WildSeal suggests using online doc. This is good but it is only useful for Python's standard libraries. I want to search all the modules installed in my current Python path. This is easy with IntelliJ. It has already indexed all the files.
I tried to use grep to search for the class inside the site-packages directory. But it takes a lot of time to search all the files, probably since they have not been indexed.
|
[
"Let us not forget about dir(), which is heavily used by those of us who use vim as our IDE. \n",
"Try inspect.getmodule:\n>>> import inspect\n>>> class Foo:\n pass\n\n>>> inspect.getmodule(Foo)\n<module '__main__' (built-in)>\n\nLots of other cool stuff in there, too.\n",
"I use ctags and I've got my site-packages as well as other folders indexed in advance. There are a number of GUI and command line tools that will integrate with ctags to do what you need. Personally, I use vim as a text editor with the TagList plugin (instructions).\n",
"The special attribute __module__ is the module name in which a class was defined. It will be '__main__' if defined in the top-level script.\n",
"You can check the online documentation, or the documentation installed with Python. If you search for a function or class, you'll get all the relevant information (I assume you meant the package or module of a class or of a function, in the Python standard library).\nThere aren't so many of them though, at least that people usually use at the same time, so you should quickly get to know them.\n"
] |
[
3,
2,
2,
1,
0
] |
[
"You can try :\nimport array\nprint(array.__dict__) \n\n"
] |
[
-2
] |
[
"python"
] |
stackoverflow_0002038002_python.txt
|
Q:
Show label value in segmented final image
I'd like to show label value in final results displaying. I segmented input image using k means clustering and output are 25 classes.
My code:
import matplotlib.pyplot as plt
from skimage.segmentation import slic
from skimage import color
img_bounds = slic(img_blurred, # filtered input image
n_segments=25,
compactness=1,
start_label=0)
plt.figure()
plt.gray()
plt.subplot(121)
plt.imshow(img_rounded) # input image
plt.subplot(122)
plt.imshow(color.label2rgb(img_bounds, img_blurred_normalized, alpha=0.5))
img_bounds contains labels for every class.
Whole code produces this output: Segmented image using Scikit-image slic
Finally, here is my question. I'd like to plot class number insude right plot, so, f.e. in center of each class appears its label. Do you have any idea, how could I achieve it?
I tried to look for function, which would do this on Matplotlib.pyplot and also on Scikit-image APIs, but I did not find any relevant informations.
A:
I don't have time to write a full answer at the moment, but your variable img_bounds will have 1 where the pixel is of class 1, and 2 where the pixel is of class 2 and so on...
You can make a binary image of the pixels in, say, class 4 with:
c4 = ((img_bounds == 4) * 255).astype(np.uint8)
import cv2
cv2.imwrite('DEBUG-class4.png', c4)
That will give you a solid black image that just has pixels of class=4 in white and save it in a debug image with OpenCV. You can then use OpenCV again to find that contour and to find its centroid:
cnts, _ = cv2.findContours(c4, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
You can then get the moments with:
M = cv2.moments(cnts[0])
And then get the centroid of the class 4 pixels with:
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
You can then draw text near that point [cX,cY] with:
cv2.putText()
or with PIL/Pillow.
Repeat for other classes. Or take the max and min x and y and draw in geometric centre rather than at centroid.
|
Show label value in segmented final image
|
I'd like to show label value in final results displaying. I segmented input image using k means clustering and output are 25 classes.
My code:
import matplotlib.pyplot as plt
from skimage.segmentation import slic
from skimage import color
img_bounds = slic(img_blurred, # filtered input image
n_segments=25,
compactness=1,
start_label=0)
plt.figure()
plt.gray()
plt.subplot(121)
plt.imshow(img_rounded) # input image
plt.subplot(122)
plt.imshow(color.label2rgb(img_bounds, img_blurred_normalized, alpha=0.5))
img_bounds contains labels for every class.
Whole code produces this output: Segmented image using Scikit-image slic
Finally, here is my question. I'd like to plot class number insude right plot, so, f.e. in center of each class appears its label. Do you have any idea, how could I achieve it?
I tried to look for function, which would do this on Matplotlib.pyplot and also on Scikit-image APIs, but I did not find any relevant informations.
|
[
"I don't have time to write a full answer at the moment, but your variable img_bounds will have 1 where the pixel is of class 1, and 2 where the pixel is of class 2 and so on...\nYou can make a binary image of the pixels in, say, class 4 with:\nc4 = ((img_bounds == 4) * 255).astype(np.uint8)\n\nimport cv2\ncv2.imwrite('DEBUG-class4.png', c4)\n\nThat will give you a solid black image that just has pixels of class=4 in white and save it in a debug image with OpenCV. You can then use OpenCV again to find that contour and to find its centroid:\ncnts, _ = cv2.findContours(c4, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\nYou can then get the moments with:\nM = cv2.moments(cnts[0])\n\nAnd then get the centroid of the class 4 pixels with:\ncX = int(M[\"m10\"] / M[\"m00\"])\ncY = int(M[\"m01\"] / M[\"m00\"])\n\nYou can then draw text near that point [cX,cY] with:\ncv2.putText()\n\nor with PIL/Pillow.\nRepeat for other classes. Or take the max and min x and y and draw in geometric centre rather than at centroid.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"scikit_image"
] |
stackoverflow_0074581701_python_scikit_image.txt
|
Q:
Python Logistic Regression Future Prediction
What would be a way to make something take data points, plot them, and show the predicted future, as such:
I tried all current algorithms available and noticed that everything is a straight (best fit) line - how does this site do it?
A:
As per this site - There are many time-series forecasting methods to choose from...
- Autoregression (AR)
- Moving Average (MA)
- Autoregressive Moving Average (ARMA)
- Autoregressive Integrated Moving Average (ARIMA)
- Seasonal Autoregressive Integrated Moving-Average (SARIMA)
- Seasonal Autoregressive Integrated Moving-Average with Exogenous Regressors (SARIMAX)
- Vector Autoregression (VAR)
- Vector Autoregression Moving-Average (VARMA)
- Vector Autoregression Moving-Average with Exogenous Regressors (VARMAX)
- Simple Exponential Smoothing (SES)
- Holt Winter’s Exponential Smoothing (HWES)
And according to this site, many different ways to plot it:
Matplotlib: Plots graphs easily on all applications using its API.
Seaborn: Versatile library based on matplotlib that allows comparison between multiple variables.
ggplot: Produces domain-specific visualizations
Bokeh: Preferred libraries for real-time streaming and data.
Plotly: Allows very interactive graphs with the help of JS.
Now I don't anticipate that you would want every possible permutation or combination of the methods above, so I would recommend doing some research on some of these, and deciding the one that best suits your needs and your goals.
|
Python Logistic Regression Future Prediction
|
What would be a way to make something take data points, plot them, and show the predicted future, as such:
I tried all current algorithms available and noticed that everything is a straight (best fit) line - how does this site do it?
|
[
"As per this site - There are many time-series forecasting methods to choose from...\n- Autoregression (AR)\n- Moving Average (MA)\n- Autoregressive Moving Average (ARMA)\n- Autoregressive Integrated Moving Average (ARIMA)\n- Seasonal Autoregressive Integrated Moving-Average (SARIMA)\n- Seasonal Autoregressive Integrated Moving-Average with Exogenous Regressors (SARIMAX)\n- Vector Autoregression (VAR)\n- Vector Autoregression Moving-Average (VARMA)\n- Vector Autoregression Moving-Average with Exogenous Regressors (VARMAX)\n- Simple Exponential Smoothing (SES)\n- Holt Winter’s Exponential Smoothing (HWES)\n\nAnd according to this site, many different ways to plot it:\nMatplotlib: Plots graphs easily on all applications using its API.\nSeaborn: Versatile library based on matplotlib that allows comparison between multiple variables.\nggplot: Produces domain-specific visualizations\nBokeh: Preferred libraries for real-time streaming and data.\nPlotly: Allows very interactive graphs with the help of JS.\n\nNow I don't anticipate that you would want every possible permutation or combination of the methods above, so I would recommend doing some research on some of these, and deciding the one that best suits your needs and your goals.\n"
] |
[
0
] |
[] |
[] |
[
"logistic_regression",
"python"
] |
stackoverflow_0074582839_logistic_regression_python.txt
|
Q:
how can i convert a list of letters into a dictionary
List that contains strings (https://i.stack.imgur.com/pOzik.png)
This is a string list of items and I want to extract the dictionary {} that is from the 6th character and after.
Should I convert list to dictionary?
data=
'[\n {\n "registration_number": "aj13870",\n "status": "registreret",\n "status_date": "2013-10-07t10:33:46.000+02:00",\n "type": "personbil",\n "use": "privat personk\\u00f8rsel",\n "first_registration": "2013-10-07+02:00",\n "vin": "wdd2042021g129692",\n "own_weight": null,\n "cerb_weight": 1655,\n "total_weight": 2195,\n "axels": 2,\n "pulling_axels": 1,\n "seats": 5,\n "coupling": false,\n "trailer_maxweight_nobrakes": 750,\n "trailer_maxweight_withbrakes": 1800,\n "doors": 4,\n "make": "mercedes-benz",\n "model": "c-klasse",\n "variant": "220 cdi blueefficiency t",\n "model_type": "204 k",\n "model_year": 2013,\n "color": "gr\\u00e5",\n "chassis_type": "stationcar",\n "engine_cylinders": 4,\n "engine_volume": 2143,\n "engine_power": 125,\n "fuel_type": "diesel",\n "registration_zipcode": "",\n "vehicle_id": 9000000000384590,\n "mot_info": {\n "type": "periodisksyn",\n "date": "2021-10-06",\n "result": "godkendt",\n "status": "aktiv",\n "status_date": "2021-10-06",\n "mileage": 106\n },\n "is_leasing": false,\n "leasing_from": null,\n "leasing_to": null\n }\n]'
If I try to find the index of the keys or values but it is a list of strings.
I tried to extract the keys and values from the dictionary but it doesn't work.
A:
First, you can make you data a python list object via json.loads():
import json
text = '[\n {\n "registration_number": "aj13870",\n "status": "registreret",\n "status_date": "2013-10-07t10:33:46.000+02:00",\n "type": "personbil",\n "use": "privat personk\\u00f8rsel",\n "first_registration": "2013-10-07+02:00",\n "vin": "wdd2042021g129692",\n "own_weight": null,\n "cerb_weight": 1655,\n "total_weight": 2195,\n "axels": 2,\n "pulling_axels": 1,\n "seats": 5,\n "coupling": false,\n "trailer_maxweight_nobrakes": 750,\n "trailer_maxweight_withbrakes": 1800,\n "doors": 4,\n "make": "mercedes-benz",\n "model": "c-klasse",\n "variant": "220 cdi blueefficiency t",\n "model_type": "204 k",\n "model_year": 2013,\n "color": "gr\\u00e5",\n "chassis_type": "stationcar",\n "engine_cylinders": 4,\n "engine_volume": 2143,\n "engine_power": 125,\n "fuel_type": "diesel",\n "registration_zipcode": "",\n "vehicle_id": 9000000000384590,\n "mot_info": {\n "type": "periodisksyn",\n "date": "2021-10-06",\n "result": "godkendt",\n "status": "aktiv",\n "status_date": "2021-10-06",\n "mileage": 106\n },\n "is_leasing": false,\n "leasing_from": null,\n "leasing_to": null\n }\n]'
text_list = json.loads(text)
After that, you can get first element of your list to achieve your dictionary:
print(text_list[0])
A:
Try reading it as a JSON string.
json.loads('[\n {\n "registration_number": "aj13870",\n "status": "registreret",\n "status_date": "2013-10-07t10:33:46.000+02:00",\n "type": "personbil",\n "use": "privat personk\\u00f8rsel",\n "first_registration": "2013-10-07+02:00",\n "vin": "wdd2042021g129692",\n "own_weight": null,\n "cerb_weight": 1655,\n "total_weight": 2195,\n "axels": 2,\n "pulling_axels": 1,\n "seats": 5,\n "coupling": false,\n "trailer_maxweight_nobrakes": 750,\n "trailer_maxweight_withbrakes": 1800,\n "doors": 4,\n "make": "mercedes-benz",\n "model": "c-klasse",\n "variant": "220 cdi blueefficiency t",\n "model_type": "204 k",\n "model_year": 2013,\n "color": "gr\\u00e5",\n "chassis_type": "stationcar",\n "engine_cylinders": 4,\n "engine_volume": 2143,\n "engine_power": 125,\n "fuel_type": "diesel",\n "registration_zipcode": "",\n "vehicle_id": 9000000000384590,\n "mot_info": {\n "type": "periodisksyn",\n "date": "2021-10-06",\n "result": "godkendt",\n "status": "aktiv",\n "status_date": "2021-10-06",\n "mileage": 106\n },\n "is_leasing": false,\n "leasing_from": null,\n "leasing_to": null\n }\n]')
For more info read: https://www.w3schools.com/python/python_json.asp
A:
Please format your input correctly:
[
{
"registration_number": "aj13870",
"status": "registreret",
"status_date": "2013-10-07t10:33:46.000+02:00",
"type": "personbil",
"use": "privat personk\u00f8rsel",
"first_registration": "2013-10-07+02:00",
"vin": "wdd2042021g129692",
"own_weight": null,
"cerb_weight": 1655,
"total_weight": 2195,
"axels": 2,
"pulling_axels": 1,
"seats": 5,
"coupling": false,
"trailer_maxweight_nobrakes": 750,
"trailer_maxweight_withbrakes": 1800,
"doors": 4,
"make": "mercedes-benz",
"model": "c-klasse",
"variant": "220 cdi blueefficiency t",
"model_type": "204 k",
"model_year": 2013,
"color": "gr\u00e5",
"chassis_type": "stationcar",
"engine_cylinders": 4,
"engine_volume": 2143,
"engine_power": 125,
"fuel_type": "diesel",
"registration_zipcode": "",
"vehicle_id": 9000000000384590,
"mot_info": {
"type": "periodisksyn",
"date": "2021-10-06",
"result": "godkendt",
"status": "aktiv",
"status_date": "2021-10-06",
"mileage": 106
},
"is_leasing": false,
"leasing_from": null,
"leasing_to": null
}
]
Please also provide what "doesn't work"
If you need any help with formatting/how to ask/etc this is the guide.
To extract keys/values from this string you first need to parse it: you can use the JSON library for this.
You can then use inbuilt functions to take get the keys and items
import json
text = ...
data = json.loads(text)
data = data[0] # the data is wrapped in a list
print(data)
print(data.keys())
print(data.items())
|
how can i convert a list of letters into a dictionary
|
List that contains strings (https://i.stack.imgur.com/pOzik.png)
This is a string list of items and I want to extract the dictionary {} that is from the 6th character and after.
Should I convert list to dictionary?
data=
'[\n {\n "registration_number": "aj13870",\n "status": "registreret",\n "status_date": "2013-10-07t10:33:46.000+02:00",\n "type": "personbil",\n "use": "privat personk\\u00f8rsel",\n "first_registration": "2013-10-07+02:00",\n "vin": "wdd2042021g129692",\n "own_weight": null,\n "cerb_weight": 1655,\n "total_weight": 2195,\n "axels": 2,\n "pulling_axels": 1,\n "seats": 5,\n "coupling": false,\n "trailer_maxweight_nobrakes": 750,\n "trailer_maxweight_withbrakes": 1800,\n "doors": 4,\n "make": "mercedes-benz",\n "model": "c-klasse",\n "variant": "220 cdi blueefficiency t",\n "model_type": "204 k",\n "model_year": 2013,\n "color": "gr\\u00e5",\n "chassis_type": "stationcar",\n "engine_cylinders": 4,\n "engine_volume": 2143,\n "engine_power": 125,\n "fuel_type": "diesel",\n "registration_zipcode": "",\n "vehicle_id": 9000000000384590,\n "mot_info": {\n "type": "periodisksyn",\n "date": "2021-10-06",\n "result": "godkendt",\n "status": "aktiv",\n "status_date": "2021-10-06",\n "mileage": 106\n },\n "is_leasing": false,\n "leasing_from": null,\n "leasing_to": null\n }\n]'
If I try to find the index of the keys or values but it is a list of strings.
I tried to extract the keys and values from the dictionary but it doesn't work.
|
[
"First, you can make you data a python list object via json.loads():\nimport json\n\n\ntext = '[\\n {\\n \"registration_number\": \"aj13870\",\\n \"status\": \"registreret\",\\n \"status_date\": \"2013-10-07t10:33:46.000+02:00\",\\n \"type\": \"personbil\",\\n \"use\": \"privat personk\\\\u00f8rsel\",\\n \"first_registration\": \"2013-10-07+02:00\",\\n \"vin\": \"wdd2042021g129692\",\\n \"own_weight\": null,\\n \"cerb_weight\": 1655,\\n \"total_weight\": 2195,\\n \"axels\": 2,\\n \"pulling_axels\": 1,\\n \"seats\": 5,\\n \"coupling\": false,\\n \"trailer_maxweight_nobrakes\": 750,\\n \"trailer_maxweight_withbrakes\": 1800,\\n \"doors\": 4,\\n \"make\": \"mercedes-benz\",\\n \"model\": \"c-klasse\",\\n \"variant\": \"220 cdi blueefficiency t\",\\n \"model_type\": \"204 k\",\\n \"model_year\": 2013,\\n \"color\": \"gr\\\\u00e5\",\\n \"chassis_type\": \"stationcar\",\\n \"engine_cylinders\": 4,\\n \"engine_volume\": 2143,\\n \"engine_power\": 125,\\n \"fuel_type\": \"diesel\",\\n \"registration_zipcode\": \"\",\\n \"vehicle_id\": 9000000000384590,\\n \"mot_info\": {\\n \"type\": \"periodisksyn\",\\n \"date\": \"2021-10-06\",\\n \"result\": \"godkendt\",\\n \"status\": \"aktiv\",\\n \"status_date\": \"2021-10-06\",\\n \"mileage\": 106\\n },\\n \"is_leasing\": false,\\n \"leasing_from\": null,\\n \"leasing_to\": null\\n }\\n]'\ntext_list = json.loads(text)\n\nAfter that, you can get first element of your list to achieve your dictionary:\nprint(text_list[0])\n\n",
"Try reading it as a JSON string.\n\njson.loads('[\\n {\\n \"registration_number\": \"aj13870\",\\n \"status\": \"registreret\",\\n \"status_date\": \"2013-10-07t10:33:46.000+02:00\",\\n \"type\": \"personbil\",\\n \"use\": \"privat personk\\\\u00f8rsel\",\\n \"first_registration\": \"2013-10-07+02:00\",\\n \"vin\": \"wdd2042021g129692\",\\n \"own_weight\": null,\\n \"cerb_weight\": 1655,\\n \"total_weight\": 2195,\\n \"axels\": 2,\\n \"pulling_axels\": 1,\\n \"seats\": 5,\\n \"coupling\": false,\\n \"trailer_maxweight_nobrakes\": 750,\\n \"trailer_maxweight_withbrakes\": 1800,\\n \"doors\": 4,\\n \"make\": \"mercedes-benz\",\\n \"model\": \"c-klasse\",\\n \"variant\": \"220 cdi blueefficiency t\",\\n \"model_type\": \"204 k\",\\n \"model_year\": 2013,\\n \"color\": \"gr\\\\u00e5\",\\n \"chassis_type\": \"stationcar\",\\n \"engine_cylinders\": 4,\\n \"engine_volume\": 2143,\\n \"engine_power\": 125,\\n \"fuel_type\": \"diesel\",\\n \"registration_zipcode\": \"\",\\n \"vehicle_id\": 9000000000384590,\\n \"mot_info\": {\\n \"type\": \"periodisksyn\",\\n \"date\": \"2021-10-06\",\\n \"result\": \"godkendt\",\\n \"status\": \"aktiv\",\\n \"status_date\": \"2021-10-06\",\\n \"mileage\": 106\\n },\\n \"is_leasing\": false,\\n \"leasing_from\": null,\\n \"leasing_to\": null\\n }\\n]')\n\nFor more info read: https://www.w3schools.com/python/python_json.asp\n",
"Please format your input correctly:\n[\n {\n \"registration_number\": \"aj13870\",\n \"status\": \"registreret\",\n \"status_date\": \"2013-10-07t10:33:46.000+02:00\",\n \"type\": \"personbil\",\n \"use\": \"privat personk\\u00f8rsel\",\n \"first_registration\": \"2013-10-07+02:00\",\n \"vin\": \"wdd2042021g129692\",\n \"own_weight\": null,\n \"cerb_weight\": 1655,\n \"total_weight\": 2195,\n \"axels\": 2,\n \"pulling_axels\": 1,\n \"seats\": 5,\n \"coupling\": false,\n \"trailer_maxweight_nobrakes\": 750,\n \"trailer_maxweight_withbrakes\": 1800,\n \"doors\": 4,\n \"make\": \"mercedes-benz\",\n \"model\": \"c-klasse\",\n \"variant\": \"220 cdi blueefficiency t\",\n \"model_type\": \"204 k\",\n \"model_year\": 2013,\n \"color\": \"gr\\u00e5\",\n \"chassis_type\": \"stationcar\",\n \"engine_cylinders\": 4,\n \"engine_volume\": 2143,\n \"engine_power\": 125,\n \"fuel_type\": \"diesel\",\n \"registration_zipcode\": \"\",\n \"vehicle_id\": 9000000000384590,\n \"mot_info\": {\n \"type\": \"periodisksyn\",\n \"date\": \"2021-10-06\",\n \"result\": \"godkendt\",\n \"status\": \"aktiv\",\n \"status_date\": \"2021-10-06\",\n \"mileage\": 106\n },\n \"is_leasing\": false,\n \"leasing_from\": null,\n \"leasing_to\": null\n }\n]\n\nPlease also provide what \"doesn't work\"\nIf you need any help with formatting/how to ask/etc this is the guide.\n\nTo extract keys/values from this string you first need to parse it: you can use the JSON library for this.\nYou can then use inbuilt functions to take get the keys and items\nimport json\ntext = ...\ndata = json.loads(text)\ndata = data[0] # the data is wrapped in a list\nprint(data)\nprint(data.keys())\nprint(data.items())\n\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"dictionary",
"list",
"python",
"string"
] |
stackoverflow_0074582893_dictionary_list_python_string.txt
|
Q:
CodeWars Challenge Error: Replacing with Alphabet Position
I am trying to solve this challenge, but my code doesn't seem to work, is there a fix? Here is the question:
In this kata you are required to, given a string, replace every letter with its position in the alphabet.
If anything in the text isn't a letter, ignore it and don't return it.
"a" = 1, "b" = 2, etc.
Example
alphabet_position("The sunset sets at twelve o' clock.")
Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" ( as a string )
Here is my code:
`
def alphabet_position(text):
new= ''
a1 = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
a2 = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
n= ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26']
for i in range(0, len(text)-1):
if i in a1:
index= a1.index(i)
new+= n[index]
elif i in a2:
index=a2.index(i)
new+= n[index]
return new
`
A:
As previous posts (@John Coleman) suggested, it's easier to just use ord to solve it:
Credit to him and earlier comments.
def alphabet_position(s):
return " ".join(str(ord(c)-ord("a")+1) for c in s.lower() if c.isalpha())
# Or you still like your original mapping approach:
def alphabet_position(text):
letters = "abcdefghijklmnopqrstuvwxyz"
return " ".join([str(letters.find(c) + 1)
for c in text.lower() if c in letters])
print(alphabet_position("The sunset sets at twelve o' clock."))
# 20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11
A:
There are 2 problems with your code:
You are comparing the numerical index of a letter with a1 and a2. No numerical index is a letter, so neither of your if branches are ever executed, which is why you always get the empty string returned. The solution is to directly iterate over the letters in text.
You aren't putting spaces between the numbers. The solution is to gather the numbers into a list and to then join them with a space delimiter.
Making these changes leads to the following code:
def alphabet_position(text):
new= []
a1 = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
a2 = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
n= ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26']
for i in text:
if i in a1:
index= a1.index(i)
new.append(n[index])
elif i in a2:
index=a2.index(i)
new.append(n[index])
return ' '.join(new)
For example
alphabet_position("The sunset sets at twelve o' clock.")
'20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11'
This answer shows how to debug your code so that it works. The answer by Daniel Hao shows a much more pythonic approach to the problem.
|
CodeWars Challenge Error: Replacing with Alphabet Position
|
I am trying to solve this challenge, but my code doesn't seem to work, is there a fix? Here is the question:
In this kata you are required to, given a string, replace every letter with its position in the alphabet.
If anything in the text isn't a letter, ignore it and don't return it.
"a" = 1, "b" = 2, etc.
Example
alphabet_position("The sunset sets at twelve o' clock.")
Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" ( as a string )
Here is my code:
`
def alphabet_position(text):
new= ''
a1 = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
a2 = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
n= ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26']
for i in range(0, len(text)-1):
if i in a1:
index= a1.index(i)
new+= n[index]
elif i in a2:
index=a2.index(i)
new+= n[index]
return new
`
|
[
"As previous posts (@John Coleman) suggested, it's easier to just use ord to solve it:\nCredit to him and earlier comments.\n\ndef alphabet_position(s):\n return \" \".join(str(ord(c)-ord(\"a\")+1) for c in s.lower() if c.isalpha())\n\n# Or you still like your original mapping approach:\n\ndef alphabet_position(text):\n letters = \"abcdefghijklmnopqrstuvwxyz\"\n \n return \" \".join([str(letters.find(c) + 1)\n for c in text.lower() if c in letters])\n\n\nprint(alphabet_position(\"The sunset sets at twelve o' clock.\"))\n\n# 20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11\n\n",
"There are 2 problems with your code:\n\nYou are comparing the numerical index of a letter with a1 and a2. No numerical index is a letter, so neither of your if branches are ever executed, which is why you always get the empty string returned. The solution is to directly iterate over the letters in text.\n\nYou aren't putting spaces between the numbers. The solution is to gather the numbers into a list and to then join them with a space delimiter.\n\n\nMaking these changes leads to the following code:\ndef alphabet_position(text):\n new= []\n a1 = [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",\"l\",\"m\",\"n\",\"o\",\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"v\",\"w\",\"x\",\"y\",\"z\"]\n a2 = [\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\"]\n n= ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26']\n for i in text:\n if i in a1:\n index= a1.index(i)\n new.append(n[index])\n elif i in a2:\n index=a2.index(i)\n new.append(n[index]) \n return ' '.join(new)\n\nFor example\nalphabet_position(\"The sunset sets at twelve o' clock.\")\n'20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11'\n\nThis answer shows how to debug your code so that it works. The answer by Daniel Hao shows a much more pythonic approach to the problem.\n"
] |
[
3,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074582552_python.txt
|
Q:
ModuleNotFoundError: No module named 'pynput' error on PyCharm
import pynput
from pynput.keyboard import Key, Listener
def keyenter(key):
print("{0} pressed".format(key))
def keyexit(key):
if key == Key.esc:
return False
with Listener(keyenter=keyenter, keyexit=keyexit) as listener:
listener.join()
I keep getting the error -- ModuleNotFoundError: No module named 'pynput'
I've been at this for a while. Even had a go at online IDE's such as online-python.com, but threw the same error.
There are similar threads on stackoverflow but none seem to have a solid fix/guide to solve this.
A:
Make sure that you did install pynput:
$ python3 -m pip install pynput
And config the Python interpreter in Pycharm correctly, to the global python3 or your specific venv.
A:
A way that worked for me is installing pynput directing from inside PyCharm by using the terminal found on the bottom right.
Inside the PyCharm terminal type:
pip3 install pynput
Note: This will only work if you already have Python3 installed on your system. Hope this helps! (:
A:
I was stuck on a similar issues for almost two days. I was new to using python so I didn't know how to use the IDE well. All that I was missing was checking off "inherit global site-packages".
After that, it worked fine
A:
I got this problem today and want to share my solution.
In my case I'm using virtual environment and I re-used the venv/ directory used in my last project, it was venv39/ and I renamed it to venv/, and copy/paste to new project, the module pytest was already in it.
Then I did pip install pynput, it looked pretty good when I used vscode or PyCharm to wrote the code, no module missing prompt from the IDE, but, when I ran pytest there's always no module named pynput.
Finally I guess the pytest.exe might be using the old python.exe or something like that, so I did pip uninstall pytest and pip install pytest, then the problem was gone.
Hope it help if you got the same case.
|
ModuleNotFoundError: No module named 'pynput' error on PyCharm
|
import pynput
from pynput.keyboard import Key, Listener
def keyenter(key):
print("{0} pressed".format(key))
def keyexit(key):
if key == Key.esc:
return False
with Listener(keyenter=keyenter, keyexit=keyexit) as listener:
listener.join()
I keep getting the error -- ModuleNotFoundError: No module named 'pynput'
I've been at this for a while. Even had a go at online IDE's such as online-python.com, but threw the same error.
There are similar threads on stackoverflow but none seem to have a solid fix/guide to solve this.
|
[
"Make sure that you did install pynput:\n$ python3 -m pip install pynput\n\nAnd config the Python interpreter in Pycharm correctly, to the global python3 or your specific venv.\n",
"A way that worked for me is installing pynput directing from inside PyCharm by using the terminal found on the bottom right.\nInside the PyCharm terminal type:\npip3 install pynput\n\nNote: This will only work if you already have Python3 installed on your system. Hope this helps! (:\n\n",
"I was stuck on a similar issues for almost two days. I was new to using python so I didn't know how to use the IDE well. All that I was missing was checking off \"inherit global site-packages\".\nAfter that, it worked fine\n",
"I got this problem today and want to share my solution.\nIn my case I'm using virtual environment and I re-used the venv/ directory used in my last project, it was venv39/ and I renamed it to venv/, and copy/paste to new project, the module pytest was already in it.\nThen I did pip install pynput, it looked pretty good when I used vscode or PyCharm to wrote the code, no module missing prompt from the IDE, but, when I ran pytest there's always no module named pynput.\nFinally I guess the pytest.exe might be using the old python.exe or something like that, so I did pip uninstall pytest and pip install pytest, then the problem was gone.\nHope it help if you got the same case.\n"
] |
[
0,
0,
0,
0
] |
[] |
[] |
[
"modulenotfounderror",
"pycharm",
"pynput",
"python"
] |
stackoverflow_0070321580_modulenotfounderror_pycharm_pynput_python.txt
|
Q:
When using CDK and a docker image, cache pip dependencies between PythonFunction builds?
The issue I'm facing is similar to https://github.com/aws/aws-cdk/issues/9406 but the resolution to that seems? to just be to use a layer.
I have about 75 Python Lambda functions which I'm deploying using CDK. The functions have a mix of dependencies from both requirements.txt and some private libraries which I copy into the directory (entry). For any functions which have changed cdk does indeed detect the change and goes ahead and spins up a docker image to run pip and do its thing, but doesn't seem to leverage any caching between function builds.
So if I change some piece of code in a base dependency (which all 75 functions depend on), then run cdk deploy, it will spin up docker and run a pip install 75 separate times. Each time pip runs it's pulling down all of the dependencies from scratch. So that's 75 times downloading requests and boto3 and everything else I depend on.
Is there a mechanism for me to share the dependencies between instances of docker spinning up?
For reference, the PythonFunction code: (https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-lambda-python-alpha.PythonFunction.html)
lambdas = {}
for this_lambda in lambda_details:
handler = _lambda.PythonFunction(
self,
this_lambda[0],
entry=this_lambda[3],
index=this_lambda[1],
handler=this_lambda[2],
runtime=Runtime.PYTHON_3_9,
architecture=Architecture.ARM_64,
bundling={
'image': DockerImage('public.ecr.aws/sam/build-python3.9:latest-arm64'),
'asset_hash_type': AssetHashType.SOURCE
}
)
lambdas[this_lambda[0]] = handler
A:
So I ended up just using the layers approach. I create one 'common' layer with most of my utility code in it, and then a couple of other layers (which come with a big dependency tree each) that are only used in a couple of places.
When building, if some common code has changed, it'll rebuild the common layer, and then update the various functions which depend on it. If I update just an individual function, just that function gets updated.
I don't like having lots of stuff bundled into a 'common' layer, but having said that it's working pretty well for me.
|
When using CDK and a docker image, cache pip dependencies between PythonFunction builds?
|
The issue I'm facing is similar to https://github.com/aws/aws-cdk/issues/9406 but the resolution to that seems? to just be to use a layer.
I have about 75 Python Lambda functions which I'm deploying using CDK. The functions have a mix of dependencies from both requirements.txt and some private libraries which I copy into the directory (entry). For any functions which have changed cdk does indeed detect the change and goes ahead and spins up a docker image to run pip and do its thing, but doesn't seem to leverage any caching between function builds.
So if I change some piece of code in a base dependency (which all 75 functions depend on), then run cdk deploy, it will spin up docker and run a pip install 75 separate times. Each time pip runs it's pulling down all of the dependencies from scratch. So that's 75 times downloading requests and boto3 and everything else I depend on.
Is there a mechanism for me to share the dependencies between instances of docker spinning up?
For reference, the PythonFunction code: (https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-lambda-python-alpha.PythonFunction.html)
lambdas = {}
for this_lambda in lambda_details:
handler = _lambda.PythonFunction(
self,
this_lambda[0],
entry=this_lambda[3],
index=this_lambda[1],
handler=this_lambda[2],
runtime=Runtime.PYTHON_3_9,
architecture=Architecture.ARM_64,
bundling={
'image': DockerImage('public.ecr.aws/sam/build-python3.9:latest-arm64'),
'asset_hash_type': AssetHashType.SOURCE
}
)
lambdas[this_lambda[0]] = handler
|
[
"So I ended up just using the layers approach. I create one 'common' layer with most of my utility code in it, and then a couple of other layers (which come with a big dependency tree each) that are only used in a couple of places.\nWhen building, if some common code has changed, it'll rebuild the common layer, and then update the various functions which depend on it. If I update just an individual function, just that function gets updated.\nI don't like having lots of stuff bundled into a 'common' layer, but having said that it's working pretty well for me.\n"
] |
[
0
] |
[] |
[] |
[
"aws_cdk",
"aws_cdk_python",
"docker",
"python"
] |
stackoverflow_0074256281_aws_cdk_aws_cdk_python_docker_python.txt
|
Q:
pygame.QUIT() - TypeError: 'int' object is not callable
I'm fairly new to python. I'm writing a code for a simple alien invasion game but I'm getting this error.
import sys
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf
def run_game():
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_caption("Game")
ship = Ship(screen)
bg_color = (230, 230, 230)
while True:
gf.check_events(ship)
ship.update()
gf.update_screen(ai_settings, screen, ship)
for event in pygame.event.get():
if event.type==pygame.QUIT():
sys.exit()
screen.fill(ai_settings.bg_color)
ship.blitme()
pygame.display.flip()
run_game()
I'm aware that I'm accidentally calling some integer value but I have no clue where I'm going wrong.
I have also checked these lines
File "C:/Users/Areeb Irfan/.PyCharmCE2018.3/config/scratches/AlienGame.py", line 25, in
run_game()
File "C:/Users/Areeb Irfan/.PyCharmCE2018.3/config/scratches/AlienGame.py", line 16, in run_game
gf.check_events(ship)
File "C:\Users\Areeb Irfan.PyCharmCE2018.3\config\scratches\game_functions.py", line 5, in check_events
if event.type==pygame.QUIT():
TypeError: 'int' object is not callable
A:
As shown in your error message, this line event.type==pygame.QUIT() is the issue. The error TypeError: 'int' object is not callable means that you are trying to call an int, which means that you are trying to treat an int as a function, which in turn means that you have parentheses () after an int value. The only place you have parentheses in that line is afer pygame.QUIT, so just remove the parentheses:
if event.type==pygame.QUIT:
A:
To fix that, remove the parentheses () at pygame.QUIT.
Get rid of them, and run the code again. It should work, as long as you don't have that same "if" somewhere else.
A:
There is a flaw in your code. You have written as:
if event.type == pygame.QUIT():
quit()
Better try using this code:
if event.type == pygame.QUIT():
quit()
(or)
if event.type == pygame.QUIT():
sys.exit()
This happens because pygame.QUIT is an integer data. Integer data is not followed by parantheses. But enclosing it with parantheses makes it to be a function which is wrong. Hope this helps you!
|
pygame.QUIT() - TypeError: 'int' object is not callable
|
I'm fairly new to python. I'm writing a code for a simple alien invasion game but I'm getting this error.
import sys
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf
def run_game():
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_caption("Game")
ship = Ship(screen)
bg_color = (230, 230, 230)
while True:
gf.check_events(ship)
ship.update()
gf.update_screen(ai_settings, screen, ship)
for event in pygame.event.get():
if event.type==pygame.QUIT():
sys.exit()
screen.fill(ai_settings.bg_color)
ship.blitme()
pygame.display.flip()
run_game()
I'm aware that I'm accidentally calling some integer value but I have no clue where I'm going wrong.
I have also checked these lines
File "C:/Users/Areeb Irfan/.PyCharmCE2018.3/config/scratches/AlienGame.py", line 25, in
run_game()
File "C:/Users/Areeb Irfan/.PyCharmCE2018.3/config/scratches/AlienGame.py", line 16, in run_game
gf.check_events(ship)
File "C:\Users\Areeb Irfan.PyCharmCE2018.3\config\scratches\game_functions.py", line 5, in check_events
if event.type==pygame.QUIT():
TypeError: 'int' object is not callable
|
[
"As shown in your error message, this line event.type==pygame.QUIT() is the issue. The error TypeError: 'int' object is not callable means that you are trying to call an int, which means that you are trying to treat an int as a function, which in turn means that you have parentheses () after an int value. The only place you have parentheses in that line is afer pygame.QUIT, so just remove the parentheses:\nif event.type==pygame.QUIT:\n\n",
"To fix that, remove the parentheses () at pygame.QUIT.\nGet rid of them, and run the code again. It should work, as long as you don't have that same \"if\" somewhere else.\n",
"There is a flaw in your code. You have written as:\nif event.type == pygame.QUIT():\n quit()\n\nBetter try using this code:\nif event.type == pygame.QUIT():\n quit()\n\n(or)\nif event.type == pygame.QUIT():\n sys.exit()\n\nThis happens because pygame.QUIT is an integer data. Integer data is not followed by parantheses. But enclosing it with parantheses makes it to be a function which is wrong. Hope this helps you!\n"
] |
[
4,
0,
0
] |
[] |
[] |
[
"pygame",
"python"
] |
stackoverflow_0057135789_pygame_python.txt
|
Q:
Two threads print even and odd numbers between 0 to 5 alternately in Python
I'm trying to get the result below running 2 threads alternately. *Between 0 to 5, thread A prints even numbers and thread B prints odd numbers (I use Python 3.8.5):
A:0
B:1
A:2
B:3
A:4
B:5
So, with global variables, locks and while statements, I created the code below to try to get the result above:
import threading
lock = threading.Lock()
owner = "A"
i = 0
def test1():
global owner, i
while i <= 5:
lock.acquire()
if owner == "A":
print(owner + ":" + str(i))
owner = "B"
i += 1
lock.release()
def test2():
global owner, i
while i <= 5:
lock.acquire()
if owner == "B":
print(owner + ":" + str(i))
owner = "A"
i += 1
lock.release()
A = threading.Thread(target=test1)
B = threading.Thread(target=test2)
A.start()
B.start()
A.join()
B.join()
But, the code above got the result below with A:6. *Thread A printed even number 6:
A:0
B:1
A:2
B:3
A:4
B:5
A:6 # Here
I couldn't find any mistakes so how can I get the proper result without A:6? And, why did I get the result with A:6?
A:
The reason you are seeing the issue, is that the thread is still within the while loop when i moves from 5 to 6. The thread seems to obtain lock before the value is updated. i.e. The speed of release and lock is quicker than the assignment of i. So the thread goes through one more round, but the only check you have is if the owner is equal to A or B. So you have to once again have the check in place to test that i<=5.
If you had a single thread, then you would not have this issue, but because you are using two threads, you have to think of them as different entities, doing their own jobs. While i is being updated in one thread, the other thread is still spinning and checking, locking and unlocking.
The best way to visualise the thread actions is to have print statements within the lock (before the if-statement) - to see what each thread is up to.
import threading
lock = threading.Lock()
owner = "A"
i = 0
def test1():
global owner, i
while i <= 5:
lock.acquire() # Here
if owner == "A" and i<=5:
print(owner + ":" + str(i))
owner = "B"
i += 1
lock.release()
def test2():
global owner, i
while i <= 5:
lock.acquire() # Here
if owner == "B" and i<=5:
print(owner + ":" + str(i))
owner = "A"
i += 1
lock.release()
A = threading.Thread(target=test1)
B = threading.Thread(target=test2)
A.start()
B.start()
A.join()
B.join()
OUTPUT:
A:0
B:1
A:2
B:3
A:4
B:5
|
Two threads print even and odd numbers between 0 to 5 alternately in Python
|
I'm trying to get the result below running 2 threads alternately. *Between 0 to 5, thread A prints even numbers and thread B prints odd numbers (I use Python 3.8.5):
A:0
B:1
A:2
B:3
A:4
B:5
So, with global variables, locks and while statements, I created the code below to try to get the result above:
import threading
lock = threading.Lock()
owner = "A"
i = 0
def test1():
global owner, i
while i <= 5:
lock.acquire()
if owner == "A":
print(owner + ":" + str(i))
owner = "B"
i += 1
lock.release()
def test2():
global owner, i
while i <= 5:
lock.acquire()
if owner == "B":
print(owner + ":" + str(i))
owner = "A"
i += 1
lock.release()
A = threading.Thread(target=test1)
B = threading.Thread(target=test2)
A.start()
B.start()
A.join()
B.join()
But, the code above got the result below with A:6. *Thread A printed even number 6:
A:0
B:1
A:2
B:3
A:4
B:5
A:6 # Here
I couldn't find any mistakes so how can I get the proper result without A:6? And, why did I get the result with A:6?
|
[
"The reason you are seeing the issue, is that the thread is still within the while loop when i moves from 5 to 6. The thread seems to obtain lock before the value is updated. i.e. The speed of release and lock is quicker than the assignment of i. So the thread goes through one more round, but the only check you have is if the owner is equal to A or B. So you have to once again have the check in place to test that i<=5.\nIf you had a single thread, then you would not have this issue, but because you are using two threads, you have to think of them as different entities, doing their own jobs. While i is being updated in one thread, the other thread is still spinning and checking, locking and unlocking.\n\n\nThe best way to visualise the thread actions is to have print statements within the lock (before the if-statement) - to see what each thread is up to.\nimport threading\nlock = threading.Lock()\nowner = \"A\"\ni = 0\n\ndef test1():\n global owner, i\n while i <= 5:\n lock.acquire() # Here\n if owner == \"A\" and i<=5:\n print(owner + \":\" + str(i))\n owner = \"B\"\n i += 1\n lock.release()\n\ndef test2():\n global owner, i\n while i <= 5:\n lock.acquire() # Here\n if owner == \"B\" and i<=5:\n print(owner + \":\" + str(i))\n owner = \"A\"\n i += 1\n lock.release()\n\nA = threading.Thread(target=test1)\nB = threading.Thread(target=test2)\n\nA.start()\nB.start()\n\nA.join()\nB.join()\n\nOUTPUT:\nA:0\nB:1\nA:2\nB:3\nA:4\nB:5\n\n"
] |
[
2
] |
[] |
[] |
[
"alternate",
"multithreading",
"python",
"python_3.x",
"python_multithreading"
] |
stackoverflow_0074582964_alternate_multithreading_python_python_3.x_python_multithreading.txt
|
Q:
How to delete dictionary values simply at a specific key 'path'?
I want to implement a function that:
Given a dictionary and an iterable of keys,
deletes the value accessed by iterating over those keys.
Originally I had tried
def delete_dictionary_value(dict, keys):
inner_value = dict
for key in keys:
inner_value = inner_value[key]
del inner_value
return dict
Thinking that since inner_value is assigned to dict by reference, we can mutate dict implcitly by mutating inner_value. However, it seems that assigning inner_value itself creates a new reference (sys.getrefcount(dict[key]) is incremented by assigning inner_value inside the loop) - the result being that the local variable assignment is deled but dict is returned unchanged.
Using inner_value = None has the same effect - presumably because this merely reassigns inner_value.
Other people have posted looking for answers to questions like:
how do I ensure that my dictionary includes no values at the key x - which might be a question about recursion for nested dictionaries, or
how do I iterate over values at a given key (different flavours of this question)
how do I access the value of the key as opposed to the keyed value in a dictionary
This is none of the above - I want to remove a specific key,value pair in a dictionary that may be nested arbitrarily deeply - but I always know the path to the key,value pair I want to delete.
The solution I have hacked together so far is:
def delete_dictionary_value(dict, keys):
base_str = f"del dict"
property_access_str = ''.join([f"['{i}']" for i in keys])
return exec(base_str + property_access_str)
Which doesn't feel right.
This also seems like pretty basic functionality - but I've not found an obvious solution. Most likely I am missing something (most likely something blindingly obvious) - please help me see.
A:
Don't use a string-evaluation approach. Try to iteratively move to the last dictionary and delete the key-value pair from it. Here a possibility:
def delete_key(d, value_path):
# move to most internal dictionary
for kp in value_path[:-1]:
if kp in dd and isinstance(d[kp], dict):
d = d[kp]
else:
e_msg = f"Key-value delete-operation failed at key '{kp}'"
raise Exception(e_msg)
# last entry check
lst_kp = value_path[-1]
if lst_kp not in d:
e_msg = f"Key-value delete-operation failed at key '{lst_kp}'"
raise Exception(e_msg)
# delete key-value of most internal dictionary
print(f'Value "{d[lst_kp]}" at position "{value_path}" deleted')
del d[lst_kp]
d = {1: 2, 2:{3: "a"}, 4: {5: 6, 6:{8:9}}}
delete_key(d, [44, 6, 0])
#Value "9" at position "[4, 6, 8]" deleted
#{1: 2, 2: {3: 'a'}, 4: {5: 6, 6: {}}}
A:
If error checking is not required at all, you just need to iterate to the penultimate key and then delete the value from there:
def del_by_path(d, keys):
for k in keys[:-1]:
d = d[k]
return d.pop(keys[-1])
d = {'a': {'b': {'c': {'d': 'Value'}}}}
del_by_path(d, 'abcd')
# 'Value'
print(d)
# {'a': {'b': {'c': {}}}}
Just for fun, here's a more "functional-style" way to do the same thing:
from functools import reduce
def del_by_path(d, keys):
*init, last = keys
return reduce(dict.get, init, d).pop(last)
|
How to delete dictionary values simply at a specific key 'path'?
|
I want to implement a function that:
Given a dictionary and an iterable of keys,
deletes the value accessed by iterating over those keys.
Originally I had tried
def delete_dictionary_value(dict, keys):
inner_value = dict
for key in keys:
inner_value = inner_value[key]
del inner_value
return dict
Thinking that since inner_value is assigned to dict by reference, we can mutate dict implcitly by mutating inner_value. However, it seems that assigning inner_value itself creates a new reference (sys.getrefcount(dict[key]) is incremented by assigning inner_value inside the loop) - the result being that the local variable assignment is deled but dict is returned unchanged.
Using inner_value = None has the same effect - presumably because this merely reassigns inner_value.
Other people have posted looking for answers to questions like:
how do I ensure that my dictionary includes no values at the key x - which might be a question about recursion for nested dictionaries, or
how do I iterate over values at a given key (different flavours of this question)
how do I access the value of the key as opposed to the keyed value in a dictionary
This is none of the above - I want to remove a specific key,value pair in a dictionary that may be nested arbitrarily deeply - but I always know the path to the key,value pair I want to delete.
The solution I have hacked together so far is:
def delete_dictionary_value(dict, keys):
base_str = f"del dict"
property_access_str = ''.join([f"['{i}']" for i in keys])
return exec(base_str + property_access_str)
Which doesn't feel right.
This also seems like pretty basic functionality - but I've not found an obvious solution. Most likely I am missing something (most likely something blindingly obvious) - please help me see.
|
[
"Don't use a string-evaluation approach. Try to iteratively move to the last dictionary and delete the key-value pair from it. Here a possibility:\ndef delete_key(d, value_path):\n # move to most internal dictionary\n for kp in value_path[:-1]:\n if kp in dd and isinstance(d[kp], dict): \n d = d[kp]\n else:\n e_msg = f\"Key-value delete-operation failed at key '{kp}'\"\n raise Exception(e_msg)\n\n # last entry check\n lst_kp = value_path[-1]\n if lst_kp not in d:\n e_msg = f\"Key-value delete-operation failed at key '{lst_kp}'\"\n raise Exception(e_msg)\n\n # delete key-value of most internal dictionary\n print(f'Value \"{d[lst_kp]}\" at position \"{value_path}\" deleted')\n del d[lst_kp]\n\n\nd = {1: 2, 2:{3: \"a\"}, 4: {5: 6, 6:{8:9}}}\n\ndelete_key(d, [44, 6, 0])\n#Value \"9\" at position \"[4, 6, 8]\" deleted\n#{1: 2, 2: {3: 'a'}, 4: {5: 6, 6: {}}}\n\n",
"If error checking is not required at all, you just need to iterate to the penultimate key and then delete the value from there:\ndef del_by_path(d, keys):\n for k in keys[:-1]:\n d = d[k]\n return d.pop(keys[-1])\n\nd = {'a': {'b': {'c': {'d': 'Value'}}}}\ndel_by_path(d, 'abcd')\n# 'Value'\nprint(d)\n# {'a': {'b': {'c': {}}}}\n\nJust for fun, here's a more \"functional-style\" way to do the same thing:\nfrom functools import reduce\ndef del_by_path(d, keys):\n *init, last = keys\n return reduce(dict.get, init, d).pop(last)\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"dictionary",
"key_value",
"python"
] |
stackoverflow_0074581982_dictionary_key_value_python.txt
|
Q:
How to create a dictionary from a CSV file, appending multiple values to three keys?
I need to be able to append multiple values from a CSV file to a dictionary that has three keys. The keys are morning, midday, and night. The values should come from each row of the CSV file.
Ideally, it should look like below.
I can't use numpy or csv modules, so those options are not available. It has to work with no imports, and I'm unsure with dictionaries and how to approach this to get the output I need.
Here is a sample of what the CSV file looks like:
{
'morning': {[5, 5, 10, 17, 20, 21]},
'midday': {[10, 20, 25, 15, 8, 3]},
'night': {[3, 5, 2, 7, 15, 29]}
}
Here is my code:
time_list = []
time_dict = {}
with open('stats.csv', 'r') as data_file:
headers = data_file.readline()
for line in data_file:
Time, VS = line.split(',')
time_list.append(int(VS))
time_dict[Time] = time_dict.get(Time, 0) + int(VS)
Appending to the list produces each value like it should, i.e.:
[2, 3, 4, 5, 6, 7, 8]
But for the dictionary, it does not show each value individually for the key it is attached to. Instead, it will take all the values for each key and add them together.
Printing the dictionary shows the following:
{'morning': 2097, 'midday': 1240, 'night': 1533}
I'm unsure of how to approach this to get the dictionary to look like the following:
{
'morning':{[5, 5, 10, 17, 20, 21]},
'midday': {[10, 20, 25, 15, 8, 3]},
'night': {[3, 5, 2, 7, 15, 29]}
}
Note: Many of the answers I have found use the csv module, which I unfortunately cannot use for this. I have to use no imports for this solution.
Also keytype of the dictionary must be int so I can peform math operations on the dictionary to find out the max, min, average etc
A:
How about changing your strategy and doing it like this:
morning_list= []
midday_list= []
night_list= []
time_dict = dict()
with open("stats.csv", "r") as data_file:
headers = data_file.readline()
for line in data_file:
Time, VS = line.split(",")
if Time == "morning":
morning_list.append(int(VS))
elif Time == "midday":
midday_list.append(int(VS))
elif Time == "night":
night_list.append(int(VS))
time_dict["morning"] = morning_list
time_dict["midday"] = midday_list
time_dict["night"] = night_list
A:
I would do it this way:
import csv
with open(fn) as csv_in:
reader=csv.reader(csv_in)
header=next(reader)
data={}
for t,vs in reader:
data.setdefault(t, []).append(int(vs))
From comment "I can't use imports":
with open(fn) as csv_in:
header=next(csv_in)
data={}
for t,vs in (line.split(',') for line in csv_in):
data.setdefault(t, []).append(int(vs))
From comment "The data is in the eighth column":
With a slight modification (and assuming Python 3) you can set *vs so that vs accepts a variable number in the expansion:
with open(fn) as csv_in:
header=next(csv_in)
data={}
for t,*vs in (line.split(',') for line in csv_in):
data.setdefault(t, []).append(int(vs[7]))
Given this file:
Time,VS
morning,1,2,3,4,5,6,7,80
morning,1,2,3,4,5,6,7,81
midday,1,2,3,4,5,6,7,90
midday,1,2,3,4,5,6,7,91
night,1,2,3,4,5,6,7,100
night,1,2,3,4,5,6,7,101
Prints:
>>> data
{'morning': [80, 81], 'midday': [90, 91], 'night': [100, 101]}
|
How to create a dictionary from a CSV file, appending multiple values to three keys?
|
I need to be able to append multiple values from a CSV file to a dictionary that has three keys. The keys are morning, midday, and night. The values should come from each row of the CSV file.
Ideally, it should look like below.
I can't use numpy or csv modules, so those options are not available. It has to work with no imports, and I'm unsure with dictionaries and how to approach this to get the output I need.
Here is a sample of what the CSV file looks like:
{
'morning': {[5, 5, 10, 17, 20, 21]},
'midday': {[10, 20, 25, 15, 8, 3]},
'night': {[3, 5, 2, 7, 15, 29]}
}
Here is my code:
time_list = []
time_dict = {}
with open('stats.csv', 'r') as data_file:
headers = data_file.readline()
for line in data_file:
Time, VS = line.split(',')
time_list.append(int(VS))
time_dict[Time] = time_dict.get(Time, 0) + int(VS)
Appending to the list produces each value like it should, i.e.:
[2, 3, 4, 5, 6, 7, 8]
But for the dictionary, it does not show each value individually for the key it is attached to. Instead, it will take all the values for each key and add them together.
Printing the dictionary shows the following:
{'morning': 2097, 'midday': 1240, 'night': 1533}
I'm unsure of how to approach this to get the dictionary to look like the following:
{
'morning':{[5, 5, 10, 17, 20, 21]},
'midday': {[10, 20, 25, 15, 8, 3]},
'night': {[3, 5, 2, 7, 15, 29]}
}
Note: Many of the answers I have found use the csv module, which I unfortunately cannot use for this. I have to use no imports for this solution.
Also keytype of the dictionary must be int so I can peform math operations on the dictionary to find out the max, min, average etc
|
[
"How about changing your strategy and doing it like this:\nmorning_list= []\nmidday_list= []\nnight_list= []\ntime_dict = dict()\n\nwith open(\"stats.csv\", \"r\") as data_file:\n headers = data_file.readline()\n\n for line in data_file:\n Time, VS = line.split(\",\")\n if Time == \"morning\":\n morning_list.append(int(VS))\n elif Time == \"midday\":\n midday_list.append(int(VS))\n elif Time == \"night\":\n night_list.append(int(VS))\n\ntime_dict[\"morning\"] = morning_list\ntime_dict[\"midday\"] = midday_list\ntime_dict[\"night\"] = night_list\n\n",
"I would do it this way:\nimport csv \n\nwith open(fn) as csv_in:\n reader=csv.reader(csv_in)\n header=next(reader)\n data={}\n for t,vs in reader:\n data.setdefault(t, []).append(int(vs))\n\n\nFrom comment \"I can't use imports\":\nwith open(fn) as csv_in:\n header=next(csv_in)\n data={}\n for t,vs in (line.split(',') for line in csv_in):\n data.setdefault(t, []).append(int(vs))\n\nFrom comment \"The data is in the eighth column\":\nWith a slight modification (and assuming Python 3) you can set *vs so that vs accepts a variable number in the expansion:\nwith open(fn) as csv_in:\n header=next(csv_in)\n data={}\n for t,*vs in (line.split(',') for line in csv_in):\n data.setdefault(t, []).append(int(vs[7]))\n\nGiven this file:\nTime,VS\nmorning,1,2,3,4,5,6,7,80\nmorning,1,2,3,4,5,6,7,81\nmidday,1,2,3,4,5,6,7,90\nmidday,1,2,3,4,5,6,7,91\nnight,1,2,3,4,5,6,7,100\nnight,1,2,3,4,5,6,7,101\n\nPrints:\n>>> data\n{'morning': [80, 81], 'midday': [90, 91], 'night': [100, 101]}\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"csv",
"dictionary",
"python"
] |
stackoverflow_0074582868_csv_dictionary_python.txt
|
Q:
How do I parse a string to a float or int?
How can I convert a str to float?
"545.2222" → 545.2222
How can I convert a str to int?
"31" → 31
For the reverse, see Convert integer to string in Python and Converting a float to a string without rounding it.
Please instead use How can I read inputs as numbers? to close duplicate questions where OP received a string from user input and immediately wants to convert it, or was hoping for input (in 3.x) to convert the type automatically.
A:
>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
A:
Python2 method to check if a string is a float:
def is_float(value):
if value is None:
return False
try:
float(value)
return True
except:
return False
For the Python3 version of is_float see: Checking if a string can be converted to float in Python
A longer and more accurate name for this function could be: is_convertible_to_float(value)
What is, and is not a float in Python may surprise you:
The below unit tests were done using python2. Check it that Python3 has different behavior for what strings are convertable to float. One confounding difference is that any number of interior underscores are now allowed: (float("1_3.4") == float(13.4)) is True
val is_float(val) Note
-------------------- ---------- --------------------------------
"" False Blank string
"127" True Passed string
True True Pure sweet Truth
"True" False Vile contemptible lie
False True So false it becomes true
"123.456" True Decimal
" -127 " True Spaces trimmed
"\t\n12\r\n" True whitespace ignored
"NaN" True Not a number
"NaNanananaBATMAN" False I am Batman
"-iNF" True Negative infinity
"123.E4" True Exponential notation
".1" True mantissa only
"1_2_3.4" False Underscores not allowed
"12 34" False Spaces not allowed on interior
"1,234" False Commas gtfo
u'\x30' True Unicode is fine.
"NULL" False Null is not special
0x3fade True Hexadecimal
"6e7777777777777" True Shrunk to infinity
"1.797693e+308" True This is max value
"infinity" True Same as inf
"infinityandBEYOND" False Extra characters wreck it
"12.34.56" False Only one dot allowed
u'四' False Japanese '4' is not a float.
"#56" False Pound sign
"56%" False Percent of what?
"0E0" True Exponential, move dot 0 places
0**0 True 0___0 Exponentiation
"-5e-5" True Raise to a negative number
"+1e1" True Plus is OK with exponent
"+1e1^5" False Fancy exponent not interpreted
"+1e1.3" False No decimals in exponent
"-+1" False Make up your mind
"(1)" False Parenthesis is bad
You think you know what numbers are? You are not so good as you think! Not big surprise.
Don't use this code on life-critical software!
Catching broad exceptions this way, killing canaries and gobbling the exception creates a tiny chance that a valid float as string will return false. The float(...) line of code can failed for any of a thousand reasons that have nothing to do with the contents of the string. But if you're writing life-critical software in a duck-typing prototype language like Python, then you've got much larger problems.
A:
def num(s):
try:
return int(s)
except ValueError:
return float(s)
A:
This is another method which deserves to be mentioned here, ast.literal_eval:
This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.
That is, a safe 'eval'
>>> import ast
>>> ast.literal_eval("545.2222")
545.2222
>>> ast.literal_eval("31")
31
A:
Localization and commas
You should consider the possibility of commas in the string representation of a number, for cases like float("545,545.2222") which throws an exception. Instead, use methods in locale to convert the strings to numbers and interpret commas correctly. The locale.atof method converts to a float in one step once the locale has been set for the desired number convention.
Example 1 -- United States number conventions
In the United States and the UK, commas can be used as a thousands separator. In this example with American locale, the comma is handled properly as a separator:
>>> import locale
>>> a = u'545,545.2222'
>>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
'en_US.UTF-8'
>>> locale.atof(a)
545545.2222
>>> int(locale.atof(a))
545545
>>>
Example 2 -- European number conventions
In the majority of countries of the world, commas are used for decimal marks instead of periods. In this example with French locale, the comma is correctly handled as a decimal mark:
>>> import locale
>>> b = u'545,2222'
>>> locale.setlocale(locale.LC_ALL, 'fr_FR')
'fr_FR'
>>> locale.atof(b)
545.2222
The method locale.atoi is also available, but the argument should be an integer.
A:
float(x) if '.' in x else int(x)
A:
If you aren't averse to third-party modules, you could check out the fastnumbers module. It provides a function called fast_real that does exactly what this question is asking for and does it faster than a pure-Python implementation:
>>> from fastnumbers import fast_real
>>> fast_real("545.2222")
545.2222
>>> type(fast_real("545.2222"))
float
>>> fast_real("31")
31
>>> type(fast_real("31"))
int
A:
Users codelogic and harley are correct, but keep in mind if you know the string is an integer (for example, 545) you can call int("545") without first casting to float.
If your strings are in a list, you could use the map function as well.
>>> x = ["545.0", "545.6", "999.2"]
>>> map(float, x)
[545.0, 545.60000000000002, 999.20000000000005]
>>>
It is only good if they're all the same type.
A:
In Python, how can I parse a numeric string like "545.2222" to its corresponding float value, 542.2222? Or parse the string "31" to an integer, 31?
I just want to know how to parse a float string to a float, and (separately) an int string to an int.
It's good that you ask to do these separately. If you're mixing them, you may be setting yourself up for problems later. The simple answer is:
"545.2222" to float:
>>> float("545.2222")
545.2222
"31" to an integer:
>>> int("31")
31
Other conversions, ints to and from strings and literals:
Conversions from various bases, and you should know the base in advance (10 is the default). Note you can prefix them with what Python expects for its literals (see below) or remove the prefix:
>>> int("0b11111", 2)
31
>>> int("11111", 2)
31
>>> int('0o37', 8)
31
>>> int('37', 8)
31
>>> int('0x1f', 16)
31
>>> int('1f', 16)
31
If you don't know the base in advance, but you do know they will have the correct prefix, Python can infer this for you if you pass 0 as the base:
>>> int("0b11111", 0)
31
>>> int('0o37', 0)
31
>>> int('0x1f', 0)
31
Non-Decimal (i.e. Integer) Literals from other Bases
If your motivation is to have your own code clearly represent hard-coded specific values, however, you may not need to convert from the bases - you can let Python do it for you automatically with the correct syntax.
You can use the apropos prefixes to get automatic conversion to integers with the following literals. These are valid for Python 2 and 3:
Binary, prefix 0b
>>> 0b11111
31
Octal, prefix 0o
>>> 0o37
31
Hexadecimal, prefix 0x
>>> 0x1f
31
This can be useful when describing binary flags, file permissions in code, or hex values for colors - for example, note no quotes:
>>> 0b10101 # binary flags
21
>>> 0o755 # read, write, execute perms for owner, read & ex for group & others
493
>>> 0xffffff # the color, white, max values for red, green, and blue
16777215
Making ambiguous Python 2 octals compatible with Python 3
If you see an integer that starts with a 0, in Python 2, this is (deprecated) octal syntax.
>>> 037
31
It is bad because it looks like the value should be 37. So in Python 3, it now raises a SyntaxError:
>>> 037
File "<stdin>", line 1
037
^
SyntaxError: invalid token
Convert your Python 2 octals to octals that work in both 2 and 3 with the 0o prefix:
>>> 0o37
31
A:
The question seems a little bit old. But let me suggest a function, parseStr, which makes something similar, that is, returns integer or float and if a given ASCII string cannot be converted to none of them it returns it untouched. The code of course might be adjusted to do only what you want:
>>> import string
>>> parseStr = lambda x: x.isalpha() and x or x.isdigit() and \
... int(x) or x.isalnum() and x or \
... len(set(string.punctuation).intersection(x)) == 1 and \
... x.count('.') == 1 and float(x) or x
>>> parseStr('123')
123
>>> parseStr('123.3')
123.3
>>> parseStr('3HC1')
'3HC1'
>>> parseStr('12.e5')
1200000.0
>>> parseStr('12$5')
'12$5'
>>> parseStr('12.2.2')
'12.2.2'
A:
float("545.2222") and int(float("545.2222"))
A:
The YAML parser can help you figure out what datatype your string is. Use yaml.load(), and then you can use type(result) to test for type:
>>> import yaml
>>> a = "545.2222"
>>> result = yaml.load(a)
>>> result
545.22220000000004
>>> type(result)
<type 'float'>
>>> b = "31"
>>> result = yaml.load(b)
>>> result
31
>>> type(result)
<type 'int'>
>>> c = "HI"
>>> result = yaml.load(c)
>>> result
'HI'
>>> type(result)
<type 'str'>
A:
I use this function for that
import ast
def parse_str(s):
try:
return ast.literal_eval(str(s))
except:
return
It will convert the string to its type
value = parse_str('1') # Returns Integer
value = parse_str('1.5') # Returns Float
A:
def get_int_or_float(v):
number_as_float = float(v)
number_as_int = int(number_as_float)
return number_as_int if number_as_float == number_as_int else number_as_float
A:
def num(s):
"""num(s)
num(3),num(3.7)-->3
num('3')-->3, num('3.7')-->3.7
num('3,700')-->ValueError
num('3a'),num('a3'),-->ValueError
num('3e4') --> 30000.0
"""
try:
return int(s)
except ValueError:
try:
return float(s)
except ValueError:
raise ValueError('argument is not a string of number')
A:
You need to take into account rounding to do this properly.
i.e. - int(5.1) => 5
int(5.6) => 5 -- wrong, should be 6 so we do int(5.6 + 0.5) => 6
def convert(n):
try:
return int(n)
except ValueError:
return float(n + 0.5)
A:
You could use json.loads:
>>> import json
>>> json.loads('123.456')
123.456
>>> type(_)
<class 'float'>
>>>
As you can see it becomes a type of float.
A:
There is also regex, because sometimes string must be prepared and normalized before casting to a number:
import re
def parseNumber(value, as_int=False):
try:
number = float(re.sub('[^.\-\d]', '', value))
if as_int:
return int(number + 0.5)
else:
return number
except ValueError:
return float('nan') # or None if you wish
Usage:
parseNumber('13,345')
> 13345.0
parseNumber('- 123 000')
> -123000.0
parseNumber('99999\n')
> 99999.0
And by the way, something to verify you have a number:
import numbers
def is_number(value):
return isinstance(value, numbers.Number)
# Will work with int, float, long, Decimal
A:
To typecast in Python use the constructor functions of the type, passing the string (or whatever value you are trying to cast) as a parameter.
For example:
>>>float("23.333")
23.333
Behind the scenes, Python is calling the objects __float__ method, which should return a float representation of the parameter. This is especially powerful, as you can define your own types (using classes) with a __float__ method so that it can be casted into a float using float(myobject).
A:
Handles hex, octal, binary, decimal, and float
This solution will handle all of the string conventions for numbers (all that I know about).
def to_number(n):
''' Convert any number representation to a number
This covers: float, decimal, hex, and octal numbers.
'''
try:
return int(str(n), 0)
except:
try:
# Python 3 doesn't accept "010" as a valid octal. You must use the
# '0o' prefix
return int('0o' + n, 0)
except:
return float(n)
This test case output illustrates what I'm talking about.
======================== CAPTURED OUTPUT =========================
to_number(3735928559) = 3735928559 == 3735928559
to_number("0xFEEDFACE") = 4277009102 == 4277009102
to_number("0x0") = 0 == 0
to_number(100) = 100 == 100
to_number("42") = 42 == 42
to_number(8) = 8 == 8
to_number("0o20") = 16 == 16
to_number("020") = 16 == 16
to_number(3.14) = 3.14 == 3.14
to_number("2.72") = 2.72 == 2.72
to_number("1e3") = 1000.0 == 1000
to_number(0.001) = 0.001 == 0.001
to_number("0xA") = 10 == 10
to_number("012") = 10 == 10
to_number("0o12") = 10 == 10
to_number("0b01010") = 10 == 10
to_number("10") = 10 == 10
to_number("10.0") = 10.0 == 10
to_number("1e1") = 10.0 == 10
Here is the test:
class test_to_number(unittest.TestCase):
def test_hex(self):
# All of the following should be converted to an integer
#
values = [
# HEX
# ----------------------
# Input | Expected
# ----------------------
(0xDEADBEEF , 3735928559), # Hex
("0xFEEDFACE", 4277009102), # Hex
("0x0" , 0), # Hex
# Decimals
# ----------------------
# Input | Expected
# ----------------------
(100 , 100), # Decimal
("42" , 42), # Decimal
]
values += [
# Octals
# ----------------------
# Input | Expected
# ----------------------
(0o10 , 8), # Octal
("0o20" , 16), # Octal
("020" , 16), # Octal
]
values += [
# Floats
# ----------------------
# Input | Expected
# ----------------------
(3.14 , 3.14), # Float
("2.72" , 2.72), # Float
("1e3" , 1000), # Float
(1e-3 , 0.001), # Float
]
values += [
# All ints
# ----------------------
# Input | Expected
# ----------------------
("0xA" , 10),
("012" , 10),
("0o12" , 10),
("0b01010" , 10),
("10" , 10),
("10.0" , 10),
("1e1" , 10),
]
for _input, expected in values:
value = to_number(_input)
if isinstance(_input, str):
cmd = 'to_number("{}")'.format(_input)
else:
cmd = 'to_number({})'.format(_input)
print("{:23} = {:10} == {:10}".format(cmd, value, expected))
self.assertEqual(value, expected)
A:
Pass your string to this function:
def string_to_number(str):
if("." in str):
try:
res = float(str)
except:
res = str
elif(str.isdigit()):
res = int(str)
else:
res = str
return(res)
It will return int, float or string depending on what was passed.
String that is an int
print(type(string_to_number("124")))
<class 'int'>
String that is a float
print(type(string_to_number("12.4")))
<class 'float'>
String that is a string
print(type(string_to_number("hello")))
<class 'str'>
String that looks like a float
print(type(string_to_number("hel.lo")))
<class 'str'>
A:
a = int(float(a)) if int(float(a)) == float(a) else float(a)
A:
This is a corrected version of Totoro's answer.
This will try to parse a string and return either int or float depending on what the string represents. It might rise parsing exceptions or have some unexpected behaviour.
def get_int_or_float(v):
number_as_float = float(v)
number_as_int = int(number_as_float)
return number_as_int if number_as_float == number_as_int else
number_as_float
A:
If you are dealing with mixed integers and floats and want a consistent way to deal with your mixed data, here is my solution with the proper docstring:
def parse_num(candidate):
"""Parse string to number if possible
It work equally well with negative and positive numbers, integers and floats.
Args:
candidate (str): string to convert
Returns:
float | int | None: float or int if possible otherwise None
"""
try:
float_value = float(candidate)
except ValueError:
return None
# Optional part if you prefer int to float when decimal part is 0
if float_value.is_integer():
return int(float_value)
# end of the optional part
return float_value
# Test
candidates = ['34.77', '-13', 'jh', '8990', '76_3234_54']
res_list = list(map(parse_num, candidates))
print('Before:')
print(candidates)
print('After:')
print(res_list)
Output:
Before:
['34.77', '-13', 'jh', '8990', '76_3234_54']
After:
[34.77, -13, None, 8990, 76323454]
A:
Use:
def num(s):
try:
for each in s:
yield int(each)
except ValueError:
yield float(each)
a = num(["123.55","345","44"])
print a.next()
print a.next()
This is the most Pythonic way I could come up with.
A:
You can simply do this by
s = '542.22'
f = float(s) # This converts string data to float data with a decimal point
print(f)
i = int(f) # This converts string data to integer data by just taking the whole number part of it
print(i)
For more information on parsing of data types check on python documentation!
A:
This is a function which will convert any object (not just str) to int or float, based on if the actual string supplied looks like int or float. Further if it's an object which has both __float and __int__ methods, it defaults to using __float__
def conv_to_num(x, num_type='asis'):
'''Converts an object to a number if possible.
num_type: int, float, 'asis'
Defaults to floating point in case of ambiguity.
'''
import numbers
is_num, is_str, is_other = [False]*3
if isinstance(x, numbers.Number):
is_num = True
elif isinstance(x, str):
is_str = True
is_other = not any([is_num, is_str])
if is_num:
res = x
elif is_str:
is_float, is_int, is_char = [False]*3
try:
res = float(x)
if '.' in x:
is_float = True
else:
is_int = True
except ValueError:
res = x
is_char = True
else:
if num_type == 'asis':
funcs = [int, float]
else:
funcs = [num_type]
for func in funcs:
try:
res = func(x)
break
except TypeError:
continue
else:
res = x
A:
By using int and float methods we can convert a string to integer and floats.
s="45.8"
print(float(s))
y='67'
print(int(y))
A:
For numbers and characters together:
string_for_int = "498 results should get"
string_for_float = "498.45645765 results should get"
First import re:
import re
# For getting the integer part:
print(int(re.search(r'\d+', string_for_int).group())) #498
# For getting the float part:
print(float(re.search(r'\d+\.\d+', string_for_float).group())) #498.45645765
For easy model:
value1 = "10"
value2 = "10.2"
print(int(value1)) # 10
print(float(value2)) # 10.2
A:
If you don't want to use third party modules the following might be the most robust solution:
def string_to_int_or_float(s):
try:
f = float(s) # replace s with str(s) if you are not sure that s is a string
except ValueError:
print("Provided string '" + s + "' is not interpretable as a literal number.")
raise
try:
i = int(str(f).rstrip('0').rstrip('.'))
except:
return f
return i
It might not be the fastest, but it handles correctly literal numbers where many other solutions fail, such as:
>>> string_to_int_or_float('789.')
789
>>> string_to_int_or_float('789.0')
789
>>> string_to_int_or_float('12.3e2')
1230
>>> string_to_int_or_float('12.3e-2')
0.123
>>> string_to_int_or_float('4560e-1')
456
>>> string_to_int_or_float('4560e-2')
45.6
|
How do I parse a string to a float or int?
|
How can I convert a str to float?
"545.2222" → 545.2222
How can I convert a str to int?
"31" → 31
For the reverse, see Convert integer to string in Python and Converting a float to a string without rounding it.
Please instead use How can I read inputs as numbers? to close duplicate questions where OP received a string from user input and immediately wants to convert it, or was hoping for input (in 3.x) to convert the type automatically.
|
[
">>> a = \"545.2222\"\n>>> float(a)\n545.22220000000004\n>>> int(float(a))\n545\n\n",
"Python2 method to check if a string is a float:\ndef is_float(value):\n if value is None:\n return False\n try:\n float(value)\n return True\n except:\n return False\n\nFor the Python3 version of is_float see: Checking if a string can be converted to float in Python\nA longer and more accurate name for this function could be: is_convertible_to_float(value)\nWhat is, and is not a float in Python may surprise you:\nThe below unit tests were done using python2. Check it that Python3 has different behavior for what strings are convertable to float. One confounding difference is that any number of interior underscores are now allowed: (float(\"1_3.4\") == float(13.4)) is True\nval is_float(val) Note\n-------------------- ---------- --------------------------------\n\"\" False Blank string\n\"127\" True Passed string\nTrue True Pure sweet Truth\n\"True\" False Vile contemptible lie\nFalse True So false it becomes true\n\"123.456\" True Decimal\n\" -127 \" True Spaces trimmed\n\"\\t\\n12\\r\\n\" True whitespace ignored\n\"NaN\" True Not a number\n\"NaNanananaBATMAN\" False I am Batman\n\"-iNF\" True Negative infinity\n\"123.E4\" True Exponential notation\n\".1\" True mantissa only\n\"1_2_3.4\" False Underscores not allowed\n\"12 34\" False Spaces not allowed on interior\n\"1,234\" False Commas gtfo\nu'\\x30' True Unicode is fine.\n\"NULL\" False Null is not special\n0x3fade True Hexadecimal\n\"6e7777777777777\" True Shrunk to infinity\n\"1.797693e+308\" True This is max value\n\"infinity\" True Same as inf\n\"infinityandBEYOND\" False Extra characters wreck it\n\"12.34.56\" False Only one dot allowed\nu'四' False Japanese '4' is not a float.\n\"#56\" False Pound sign\n\"56%\" False Percent of what?\n\"0E0\" True Exponential, move dot 0 places\n0**0 True 0___0 Exponentiation\n\"-5e-5\" True Raise to a negative number\n\"+1e1\" True Plus is OK with exponent\n\"+1e1^5\" False Fancy exponent not interpreted\n\"+1e1.3\" False No decimals in exponent\n\"-+1\" False Make up your mind\n\"(1)\" False Parenthesis is bad\n\nYou think you know what numbers are? You are not so good as you think! Not big surprise.\nDon't use this code on life-critical software!\nCatching broad exceptions this way, killing canaries and gobbling the exception creates a tiny chance that a valid float as string will return false. The float(...) line of code can failed for any of a thousand reasons that have nothing to do with the contents of the string. But if you're writing life-critical software in a duck-typing prototype language like Python, then you've got much larger problems.\n",
"def num(s):\n try:\n return int(s)\n except ValueError:\n return float(s)\n\n",
"This is another method which deserves to be mentioned here, ast.literal_eval:\n\nThis can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.\n\nThat is, a safe 'eval'\n>>> import ast\n>>> ast.literal_eval(\"545.2222\")\n545.2222\n>>> ast.literal_eval(\"31\")\n31\n\n",
"Localization and commas\nYou should consider the possibility of commas in the string representation of a number, for cases like float(\"545,545.2222\") which throws an exception. Instead, use methods in locale to convert the strings to numbers and interpret commas correctly. The locale.atof method converts to a float in one step once the locale has been set for the desired number convention.\nExample 1 -- United States number conventions \nIn the United States and the UK, commas can be used as a thousands separator. In this example with American locale, the comma is handled properly as a separator:\n>>> import locale\n>>> a = u'545,545.2222'\n>>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')\n'en_US.UTF-8'\n>>> locale.atof(a)\n545545.2222\n>>> int(locale.atof(a))\n545545\n>>>\n\nExample 2 -- European number conventions\nIn the majority of countries of the world, commas are used for decimal marks instead of periods. In this example with French locale, the comma is correctly handled as a decimal mark:\n>>> import locale\n>>> b = u'545,2222'\n>>> locale.setlocale(locale.LC_ALL, 'fr_FR')\n'fr_FR'\n>>> locale.atof(b)\n545.2222\n\nThe method locale.atoi is also available, but the argument should be an integer.\n",
"float(x) if '.' in x else int(x)\n\n",
"If you aren't averse to third-party modules, you could check out the fastnumbers module. It provides a function called fast_real that does exactly what this question is asking for and does it faster than a pure-Python implementation:\n>>> from fastnumbers import fast_real\n>>> fast_real(\"545.2222\")\n545.2222\n>>> type(fast_real(\"545.2222\"))\nfloat\n>>> fast_real(\"31\")\n31\n>>> type(fast_real(\"31\"))\nint\n\n",
"Users codelogic and harley are correct, but keep in mind if you know the string is an integer (for example, 545) you can call int(\"545\") without first casting to float.\nIf your strings are in a list, you could use the map function as well. \n>>> x = [\"545.0\", \"545.6\", \"999.2\"]\n>>> map(float, x)\n[545.0, 545.60000000000002, 999.20000000000005]\n>>>\n\nIt is only good if they're all the same type.\n",
"\nIn Python, how can I parse a numeric string like \"545.2222\" to its corresponding float value, 542.2222? Or parse the string \"31\" to an integer, 31?\n I just want to know how to parse a float string to a float, and (separately) an int string to an int.\n\nIt's good that you ask to do these separately. If you're mixing them, you may be setting yourself up for problems later. The simple answer is:\n\"545.2222\" to float:\n>>> float(\"545.2222\")\n545.2222\n\n\"31\" to an integer:\n>>> int(\"31\")\n31\n\nOther conversions, ints to and from strings and literals:\nConversions from various bases, and you should know the base in advance (10 is the default). Note you can prefix them with what Python expects for its literals (see below) or remove the prefix:\n>>> int(\"0b11111\", 2)\n31\n>>> int(\"11111\", 2)\n31\n>>> int('0o37', 8)\n31\n>>> int('37', 8)\n31\n>>> int('0x1f', 16)\n31\n>>> int('1f', 16)\n31\n\nIf you don't know the base in advance, but you do know they will have the correct prefix, Python can infer this for you if you pass 0 as the base:\n>>> int(\"0b11111\", 0)\n31\n>>> int('0o37', 0)\n31\n>>> int('0x1f', 0)\n31\n\nNon-Decimal (i.e. Integer) Literals from other Bases\nIf your motivation is to have your own code clearly represent hard-coded specific values, however, you may not need to convert from the bases - you can let Python do it for you automatically with the correct syntax.\nYou can use the apropos prefixes to get automatic conversion to integers with the following literals. These are valid for Python 2 and 3:\nBinary, prefix 0b\n>>> 0b11111\n31\n\nOctal, prefix 0o\n>>> 0o37\n31\n\nHexadecimal, prefix 0x\n>>> 0x1f\n31\n\nThis can be useful when describing binary flags, file permissions in code, or hex values for colors - for example, note no quotes:\n>>> 0b10101 # binary flags\n21\n>>> 0o755 # read, write, execute perms for owner, read & ex for group & others\n493\n>>> 0xffffff # the color, white, max values for red, green, and blue\n16777215\n\nMaking ambiguous Python 2 octals compatible with Python 3\nIf you see an integer that starts with a 0, in Python 2, this is (deprecated) octal syntax.\n>>> 037\n31\n\nIt is bad because it looks like the value should be 37. So in Python 3, it now raises a SyntaxError:\n>>> 037\n File \"<stdin>\", line 1\n 037\n ^\nSyntaxError: invalid token\n\nConvert your Python 2 octals to octals that work in both 2 and 3 with the 0o prefix:\n>>> 0o37\n31\n\n",
"The question seems a little bit old. But let me suggest a function, parseStr, which makes something similar, that is, returns integer or float and if a given ASCII string cannot be converted to none of them it returns it untouched. The code of course might be adjusted to do only what you want:\n >>> import string\n >>> parseStr = lambda x: x.isalpha() and x or x.isdigit() and \\\n ... int(x) or x.isalnum() and x or \\\n ... len(set(string.punctuation).intersection(x)) == 1 and \\\n ... x.count('.') == 1 and float(x) or x\n >>> parseStr('123')\n 123\n >>> parseStr('123.3')\n 123.3\n >>> parseStr('3HC1')\n '3HC1'\n >>> parseStr('12.e5')\n 1200000.0\n >>> parseStr('12$5')\n '12$5'\n >>> parseStr('12.2.2')\n '12.2.2'\n\n",
"float(\"545.2222\") and int(float(\"545.2222\"))\n",
"The YAML parser can help you figure out what datatype your string is. Use yaml.load(), and then you can use type(result) to test for type:\n>>> import yaml\n\n>>> a = \"545.2222\"\n>>> result = yaml.load(a)\n>>> result\n545.22220000000004\n>>> type(result)\n<type 'float'>\n\n>>> b = \"31\"\n>>> result = yaml.load(b)\n>>> result\n31\n>>> type(result)\n<type 'int'>\n\n>>> c = \"HI\"\n>>> result = yaml.load(c)\n>>> result\n'HI'\n>>> type(result)\n<type 'str'>\n\n",
"I use this function for that\nimport ast\n\ndef parse_str(s):\n try:\n return ast.literal_eval(str(s))\n except:\n return\n\nIt will convert the string to its type\nvalue = parse_str('1') # Returns Integer\nvalue = parse_str('1.5') # Returns Float\n\n",
"def get_int_or_float(v):\n number_as_float = float(v)\n number_as_int = int(number_as_float)\n return number_as_int if number_as_float == number_as_int else number_as_float\n\n",
"def num(s):\n \"\"\"num(s)\n num(3),num(3.7)-->3\n num('3')-->3, num('3.7')-->3.7\n num('3,700')-->ValueError\n num('3a'),num('a3'),-->ValueError\n num('3e4') --> 30000.0\n \"\"\"\n try:\n return int(s)\n except ValueError:\n try:\n return float(s)\n except ValueError:\n raise ValueError('argument is not a string of number')\n\n",
"You need to take into account rounding to do this properly.\ni.e. - int(5.1) => 5\nint(5.6) => 5 -- wrong, should be 6 so we do int(5.6 + 0.5) => 6\ndef convert(n):\n try:\n return int(n)\n except ValueError:\n return float(n + 0.5)\n\n",
"You could use json.loads:\n>>> import json\n>>> json.loads('123.456')\n123.456\n>>> type(_)\n<class 'float'>\n>>> \n\nAs you can see it becomes a type of float.\n",
"There is also regex, because sometimes string must be prepared and normalized before casting to a number:\nimport re\n\ndef parseNumber(value, as_int=False):\n try:\n number = float(re.sub('[^.\\-\\d]', '', value))\n if as_int:\n return int(number + 0.5)\n else:\n return number\n except ValueError:\n return float('nan') # or None if you wish\n\nUsage:\nparseNumber('13,345')\n> 13345.0\n\nparseNumber('- 123 000')\n> -123000.0\n\nparseNumber('99999\\n')\n> 99999.0\n\nAnd by the way, something to verify you have a number:\nimport numbers\ndef is_number(value):\n return isinstance(value, numbers.Number)\n # Will work with int, float, long, Decimal\n\n",
"To typecast in Python use the constructor functions of the type, passing the string (or whatever value you are trying to cast) as a parameter.\nFor example:\n>>>float(\"23.333\")\n 23.333\n\nBehind the scenes, Python is calling the objects __float__ method, which should return a float representation of the parameter. This is especially powerful, as you can define your own types (using classes) with a __float__ method so that it can be casted into a float using float(myobject).\n",
"Handles hex, octal, binary, decimal, and float\nThis solution will handle all of the string conventions for numbers (all that I know about).\ndef to_number(n):\n ''' Convert any number representation to a number\n This covers: float, decimal, hex, and octal numbers.\n '''\n\n try:\n return int(str(n), 0)\n except:\n try:\n # Python 3 doesn't accept \"010\" as a valid octal. You must use the\n # '0o' prefix\n return int('0o' + n, 0)\n except:\n return float(n)\n\nThis test case output illustrates what I'm talking about.\n======================== CAPTURED OUTPUT =========================\nto_number(3735928559) = 3735928559 == 3735928559\nto_number(\"0xFEEDFACE\") = 4277009102 == 4277009102\nto_number(\"0x0\") = 0 == 0\nto_number(100) = 100 == 100\nto_number(\"42\") = 42 == 42\nto_number(8) = 8 == 8\nto_number(\"0o20\") = 16 == 16\nto_number(\"020\") = 16 == 16\nto_number(3.14) = 3.14 == 3.14\nto_number(\"2.72\") = 2.72 == 2.72\nto_number(\"1e3\") = 1000.0 == 1000\nto_number(0.001) = 0.001 == 0.001\nto_number(\"0xA\") = 10 == 10\nto_number(\"012\") = 10 == 10\nto_number(\"0o12\") = 10 == 10\nto_number(\"0b01010\") = 10 == 10\nto_number(\"10\") = 10 == 10\nto_number(\"10.0\") = 10.0 == 10\nto_number(\"1e1\") = 10.0 == 10\n\nHere is the test:\nclass test_to_number(unittest.TestCase):\n\n def test_hex(self):\n # All of the following should be converted to an integer\n #\n values = [\n\n # HEX\n # ----------------------\n # Input | Expected\n # ----------------------\n (0xDEADBEEF , 3735928559), # Hex\n (\"0xFEEDFACE\", 4277009102), # Hex\n (\"0x0\" , 0), # Hex\n\n # Decimals\n # ----------------------\n # Input | Expected\n # ----------------------\n (100 , 100), # Decimal\n (\"42\" , 42), # Decimal\n ]\n\n\n\n values += [\n # Octals\n # ----------------------\n # Input | Expected\n # ----------------------\n (0o10 , 8), # Octal\n (\"0o20\" , 16), # Octal\n (\"020\" , 16), # Octal\n ]\n\n\n values += [\n # Floats\n # ----------------------\n # Input | Expected\n # ----------------------\n (3.14 , 3.14), # Float\n (\"2.72\" , 2.72), # Float\n (\"1e3\" , 1000), # Float\n (1e-3 , 0.001), # Float\n ]\n\n values += [\n # All ints\n # ----------------------\n # Input | Expected\n # ----------------------\n (\"0xA\" , 10),\n (\"012\" , 10),\n (\"0o12\" , 10),\n (\"0b01010\" , 10),\n (\"10\" , 10),\n (\"10.0\" , 10),\n (\"1e1\" , 10),\n ]\n\n for _input, expected in values:\n value = to_number(_input)\n\n if isinstance(_input, str):\n cmd = 'to_number(\"{}\")'.format(_input)\n else:\n cmd = 'to_number({})'.format(_input)\n\n print(\"{:23} = {:10} == {:10}\".format(cmd, value, expected))\n self.assertEqual(value, expected)\n\n",
"Pass your string to this function:\ndef string_to_number(str):\n if(\".\" in str):\n try:\n res = float(str)\n except:\n res = str\n elif(str.isdigit()):\n res = int(str)\n else:\n res = str\n return(res)\n\nIt will return int, float or string depending on what was passed.\nString that is an int\nprint(type(string_to_number(\"124\")))\n<class 'int'>\n\nString that is a float\nprint(type(string_to_number(\"12.4\")))\n<class 'float'>\n\nString that is a string\nprint(type(string_to_number(\"hello\")))\n<class 'str'>\n\nString that looks like a float\nprint(type(string_to_number(\"hel.lo\")))\n<class 'str'>\n\n",
"a = int(float(a)) if int(float(a)) == float(a) else float(a)\n\n",
"This is a corrected version of Totoro's answer.\nThis will try to parse a string and return either int or float depending on what the string represents. It might rise parsing exceptions or have some unexpected behaviour.\n def get_int_or_float(v):\n number_as_float = float(v)\n number_as_int = int(number_as_float)\n return number_as_int if number_as_float == number_as_int else\n number_as_float\n\n",
"If you are dealing with mixed integers and floats and want a consistent way to deal with your mixed data, here is my solution with the proper docstring:\ndef parse_num(candidate):\n \"\"\"Parse string to number if possible\n It work equally well with negative and positive numbers, integers and floats.\n\n Args:\n candidate (str): string to convert\n\n Returns:\n float | int | None: float or int if possible otherwise None\n \"\"\"\n try:\n float_value = float(candidate)\n except ValueError:\n return None\n\n # Optional part if you prefer int to float when decimal part is 0\n if float_value.is_integer():\n return int(float_value)\n # end of the optional part\n\n return float_value\n\n# Test\ncandidates = ['34.77', '-13', 'jh', '8990', '76_3234_54']\nres_list = list(map(parse_num, candidates))\nprint('Before:')\nprint(candidates)\nprint('After:')\nprint(res_list)\n\nOutput:\nBefore:\n['34.77', '-13', 'jh', '8990', '76_3234_54']\n\nAfter:\n[34.77, -13, None, 8990, 76323454]\n\n",
"Use:\ndef num(s):\n try:\n for each in s:\n yield int(each)\n except ValueError:\n yield float(each)\na = num([\"123.55\",\"345\",\"44\"])\nprint a.next()\nprint a.next()\n\nThis is the most Pythonic way I could come up with. \n",
"You can simply do this by\ns = '542.22'\n\nf = float(s) # This converts string data to float data with a decimal point\nprint(f) \n\ni = int(f) # This converts string data to integer data by just taking the whole number part of it\nprint(i) \n\nFor more information on parsing of data types check on python documentation!\n",
"This is a function which will convert any object (not just str) to int or float, based on if the actual string supplied looks like int or float. Further if it's an object which has both __float and __int__ methods, it defaults to using __float__\ndef conv_to_num(x, num_type='asis'):\n '''Converts an object to a number if possible.\n num_type: int, float, 'asis'\n Defaults to floating point in case of ambiguity.\n '''\n import numbers\n\n is_num, is_str, is_other = [False]*3\n\n if isinstance(x, numbers.Number):\n is_num = True\n elif isinstance(x, str):\n is_str = True\n\n is_other = not any([is_num, is_str])\n\n if is_num:\n res = x\n elif is_str:\n is_float, is_int, is_char = [False]*3\n try:\n res = float(x)\n if '.' in x:\n is_float = True\n else:\n is_int = True\n except ValueError:\n res = x\n is_char = True\n\n else:\n if num_type == 'asis':\n funcs = [int, float]\n else:\n funcs = [num_type]\n\n for func in funcs:\n try:\n res = func(x)\n break\n except TypeError:\n continue\n else:\n res = x\n\n",
"By using int and float methods we can convert a string to integer and floats.\ns=\"45.8\"\nprint(float(s))\n\ny='67'\nprint(int(y))\n\n",
"For numbers and characters together:\nstring_for_int = \"498 results should get\"\nstring_for_float = \"498.45645765 results should get\"\n\nFirst import re:\n import re\n\n # For getting the integer part:\n print(int(re.search(r'\\d+', string_for_int).group())) #498\n\n # For getting the float part:\n print(float(re.search(r'\\d+\\.\\d+', string_for_float).group())) #498.45645765\n\nFor easy model:\nvalue1 = \"10\"\nvalue2 = \"10.2\"\nprint(int(value1)) # 10\nprint(float(value2)) # 10.2\n\n",
"If you don't want to use third party modules the following might be the most robust solution:\ndef string_to_int_or_float(s):\n try:\n f = float(s) # replace s with str(s) if you are not sure that s is a string\n except ValueError:\n print(\"Provided string '\" + s + \"' is not interpretable as a literal number.\")\n raise\n try:\n i = int(str(f).rstrip('0').rstrip('.'))\n except:\n return f\n return i\n\nIt might not be the fastest, but it handles correctly literal numbers where many other solutions fail, such as:\n>>> string_to_int_or_float('789.')\n789\n>>> string_to_int_or_float('789.0')\n789\n>>> string_to_int_or_float('12.3e2')\n1230\n>>> string_to_int_or_float('12.3e-2')\n0.123\n>>> string_to_int_or_float('4560e-1')\n456\n>>> string_to_int_or_float('4560e-2')\n45.6\n\n"
] |
[
3020,
589,
572,
161,
83,
82,
35,
27,
27,
21,
19,
17,
14,
11,
8,
7,
7,
6,
6,
6,
6,
4,
3,
2,
1,
1,
0,
0,
0,
0
] |
[
"Use:\n>>> str_float = \"545.2222\"\n>>> float(str_float)\n545.2222\n>>> type(_) # Check its type\n<type 'float'>\n\n>>> str_int = \"31\"\n>>> int(str_int)\n31\n>>> type(_) # Check its type\n<type 'int'>\n\n",
"Here's another interpretation of your question (hint: it's vague). It's possible you're looking for something like this:\ndef parseIntOrFloat( aString ):\n return eval( aString )\n\nIt works like this...\n>>> parseIntOrFloat(\"545.2222\")\n545.22220000000004\n>>> parseIntOrFloat(\"545\")\n545\n\n\nTheoretically, there's an injection vulnerability. The string could, for example be \"import os; os.abort()\". Without any background on where the string comes from, however, the possibility is theoretical speculation. Since the question is vague, it's not at all clear if this vulnerability actually exists or not.\n"
] |
[
-1,
-12
] |
[
"floating_point",
"integer",
"parsing",
"python",
"type_conversion"
] |
stackoverflow_0000379906_floating_point_integer_parsing_python_type_conversion.txt
|
Q:
msvcrt Module equivalent on Ubuntu
With python on windows, I have been making a game. However, this game requires the msvcrt module, which is only available on windows. I need the function msvcrt.getch(). If I was to make it possible to run this game on Ubuntu, or any linux computer in general, what module, if any, would I be able to use? I would be fine with it not working on a linux, but I would really like to find out a way. Again, is there a module, or any tools I can use, to use the msvcrt.getch function on ubuntu?
A:
The library msvcrs is only available on Windows. If you want to use a release for Ubuntu, check getch function.
import getch
This function get the pressed-key in keyboard.
Hope it help!
A:
From the command line, if necessary (as Luan Souza said above):
pip install getch
In your code:
try:
from getch import getch, getche # Linux
except ImportError:
from msvcrt import getch, getche # Windows
|
msvcrt Module equivalent on Ubuntu
|
With python on windows, I have been making a game. However, this game requires the msvcrt module, which is only available on windows. I need the function msvcrt.getch(). If I was to make it possible to run this game on Ubuntu, or any linux computer in general, what module, if any, would I be able to use? I would be fine with it not working on a linux, but I would really like to find out a way. Again, is there a module, or any tools I can use, to use the msvcrt.getch function on ubuntu?
|
[
"The library msvcrs is only available on Windows. If you want to use a release for Ubuntu, check getch function.\nimport getch\n\nThis function get the pressed-key in keyboard.\nHope it help!\n",
"From the command line, if necessary (as Luan Souza said above):\npip install getch\n\nIn your code:\ntry:\n from getch import getch, getche # Linux\nexcept ImportError:\n from msvcrt import getch, getche # Windows\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"linux",
"python",
"ubuntu"
] |
stackoverflow_0038172907_linux_python_ubuntu.txt
|
Q:
AttributeError: module 'cv2.cv2' has no attribute 'cv'
I think I have some issues with the windows system or python 3.6 version. I am facing some attribute error. I have checked and double checked my code and there is no error and i also compare my code to others and i have seen there is no error. then why i am facing this kind of error. I am adding my code here:
and i am facing following error.
C:\Users\MAN\AppData\Local\Programs\Python\Python36\python.exe
C:/Users/MAN/PycharmProjects/facerecognition/Recognise/recognizerr.py
Traceback (most recent call last): File
"C:/Users/MAN/PycharmProjects/facerecognition/Recognise/recognizerr.py",
line 11, in
font = cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1) AttributeError: module 'cv2.cv2' has no attribute 'cv'
Process finished with exit code 1
Is this the Windows issue or it shows only error in Python 3.6 version?
for you kind information I am using Python 3.6 in Windows platform.
A:
in Opencv3 the cv module is deprecated. So, in line 11 you can initialize the font like following:
font = cv2.FONT_HERSHEY_SIMPLEX
A:
font = cv2.cv.CV_FONT_HERSHEY_SIMPLEX
I worked on different variable (CV_CAP_PROP_FRAME_WIDTH), and it took me soo long to understand that you also need to remove the "CV_".
A:
Worked for me with
font = cv2.FONT_HERSHEY_SIMPLEX
as the best answer suggested.
|
AttributeError: module 'cv2.cv2' has no attribute 'cv'
|
I think I have some issues with the windows system or python 3.6 version. I am facing some attribute error. I have checked and double checked my code and there is no error and i also compare my code to others and i have seen there is no error. then why i am facing this kind of error. I am adding my code here:
and i am facing following error.
C:\Users\MAN\AppData\Local\Programs\Python\Python36\python.exe
C:/Users/MAN/PycharmProjects/facerecognition/Recognise/recognizerr.py
Traceback (most recent call last): File
"C:/Users/MAN/PycharmProjects/facerecognition/Recognise/recognizerr.py",
line 11, in
font = cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1) AttributeError: module 'cv2.cv2' has no attribute 'cv'
Process finished with exit code 1
Is this the Windows issue or it shows only error in Python 3.6 version?
for you kind information I am using Python 3.6 in Windows platform.
|
[
"in Opencv3 the cv module is deprecated. So, in line 11 you can initialize the font like following:\nfont = cv2.FONT_HERSHEY_SIMPLEX\n\n",
"font = cv2.cv.CV_FONT_HERSHEY_SIMPLEX\nI worked on different variable (CV_CAP_PROP_FRAME_WIDTH), and it took me soo long to understand that you also need to remove the \"CV_\".\n",
"Worked for me with\nfont = cv2.FONT_HERSHEY_SIMPLEX\nas the best answer suggested.\n"
] |
[
22,
5,
0
] |
[] |
[] |
[
"opencv",
"python"
] |
stackoverflow_0044640911_opencv_python.txt
|
Q:
Catch an exception if no debugger is attached
Is it possible to catch an exception in Python only if a debugger is not attached, and bypass it to the debugger otherwise?
An equivalent C# code:
// Entry point
try
{
...
}
catch (Exception e) when (!Debugger.IsAttached)
{
MessageBox.Show(e);
}
A:
You could check if you are having a Debugger. The question how that is done was awnsered here: How to detect that Python code is being executed through the debugger?
if not you gould pass the error thorug by using raise and the e object.
try:
pass
except Exception as e:
if !Debugger.IsAttached:
MessageBox.Show(e);
else:
raise e
More on that you could find here: How to re-raise an exception in nested try/except blocks?
|
Catch an exception if no debugger is attached
|
Is it possible to catch an exception in Python only if a debugger is not attached, and bypass it to the debugger otherwise?
An equivalent C# code:
// Entry point
try
{
...
}
catch (Exception e) when (!Debugger.IsAttached)
{
MessageBox.Show(e);
}
|
[
"You could check if you are having a Debugger. The question how that is done was awnsered here: How to detect that Python code is being executed through the debugger?\nif not you gould pass the error thorug by using raise and the e object.\ntry:\n pass\nexcept Exception as e:\n if !Debugger.IsAttached:\n MessageBox.Show(e);\n else:\n raise e\n\nMore on that you could find here: How to re-raise an exception in nested try/except blocks?\n"
] |
[
1
] |
[] |
[] |
[
"exception",
"python"
] |
stackoverflow_0074583075_exception_python.txt
|
Q:
How to write the coding problem with python?
Three empty cans can be exchanged for a new one. Suppose you have N cans of soda, try to use the program to solve how many cans of soda you can drink in the end?
Input description: Input a positive integer N. ex.5 / ex.100
Output description: The maximum number of sodas that can be drunk, and must have a newline character at the end. ex.7 / ex.149
`
n = int(input())
a = n-3
sum = 0
while a > 2 :
sum += 1
a -= 3
print(f'{n+sum}')
if a == 2 :
print(f'{n+sum+1}')
`
I used while to finish the code which is on above, but I input 5 and output 6,and it is actually to be 7.The other side, I input 100 and output 132. Actually, the correct answer is 149.
A:
You can try this way -
def get_total_cans(n):
s = n # we can get at least n cans
while n > 2:
s += 1
n -= 3 # 3 exchanged
n += 1 # got 1 for the exchange
return s
n = int(input())
print(get_total_cans(n))
The logic is simple and comments are added to explain.
In your code, the first thing to notice it generates wrong output when n is less than 3. For example for n = 2, your output is 3 which is not possible. Also in the while loop you are decrementing a by 3 for the exchange but you fail to add 1 to a for the one soda you can exchanging 3 empty cans. That is the issue. My above code addresses those issues
A:
Here's a recursive approach:
def dr_cans(full, empty=0):
# if we have at least 3 empty cans, exchange them for a full one
if empty >=3:
return dr_cans(full+1,empty-3)
# no full cans, and not enough empty ones
if full == 0:
return 0
# at least one full can: drink it and gain an empty one
return 1 + dr_cans(full-1, empty+1)
A:
If I understand corretly the question is as follows:
Let k be the index of the exchange process. Since not all N can be divided by 3 we have N[k] = floor(M/3), where M=N[k-1]+R[k-1] new cans in each step. Plus some R[k] = M%3 leftover cans, where % is the modulo operator...
With this is should be quite easy...
def compute_num_cans(empty_cans: int, exchange: int = 3) -> tuple:
"""
:param empty_cans: The number of cans to exchange
:return: tuple of (full_cans, empty_cans), where the empty cans are < exchange rate
"""
leftovers = empty_cans % exchange
full = empty_cans // exchange
return full, leftovers
EXCHANGE = 3
NUM_CANS = 51
print(f'Start with {NUM_CANS} and an exchange rate of {EXCHANGE}:1')
current_cans = NUM_CANS
drunk_cans = NUM_CANS
leftovers = 0
steps = 0
while current_cans >= EXCHANGE:
full, leftovers = compute_num_cans(current_cans, exchange=EXCHANGE)
current_cans = full + leftovers
drunk_cans += full
steps += 1
print(f'Cans drunk: {drunk_cans}, leftover cans: {leftovers}.')
print(f'A total of {steps} exchanges was needed.')
This yields as output
# Start with 51 and an exchange rate of 3:1
# Cans drunk: 76, leftover cans: 0.
# A total of 4 exchanges was needed.
A:
General Answer:- Accepted also if we change the numExchange also.
Code:-
def numWaterBottles(numBottles: int, numExchange: int) -> int:
ans=numBottles #Initial bottles he/she will drink
while numBottles>=numExchange: #If numBottles<numExchange exit the while loop
remainder=numBottles%numExchange #remaining bottles which is not change
numBottles//=numExchange #The bottles which are changed
ans+=numBottles #The bottles which are changed added to the answer
numBottles+=remainder #Remaining bottles==The bottles which is not change+The bottles which are changed
return ans #Return The answer
print(numWaterBottles(5,3))
print(numWaterBottles(100,3))
print(numWaterBottles(32,4)) #numexchange when different
Output:-
7
149
42
|
How to write the coding problem with python?
|
Three empty cans can be exchanged for a new one. Suppose you have N cans of soda, try to use the program to solve how many cans of soda you can drink in the end?
Input description: Input a positive integer N. ex.5 / ex.100
Output description: The maximum number of sodas that can be drunk, and must have a newline character at the end. ex.7 / ex.149
`
n = int(input())
a = n-3
sum = 0
while a > 2 :
sum += 1
a -= 3
print(f'{n+sum}')
if a == 2 :
print(f'{n+sum+1}')
`
I used while to finish the code which is on above, but I input 5 and output 6,and it is actually to be 7.The other side, I input 100 and output 132. Actually, the correct answer is 149.
|
[
"You can try this way -\ndef get_total_cans(n):\n s = n # we can get at least n cans\n while n > 2:\n s += 1\n n -= 3 # 3 exchanged\n n += 1 # got 1 for the exchange\n return s\n\nn = int(input())\nprint(get_total_cans(n))\n\nThe logic is simple and comments are added to explain.\nIn your code, the first thing to notice it generates wrong output when n is less than 3. For example for n = 2, your output is 3 which is not possible. Also in the while loop you are decrementing a by 3 for the exchange but you fail to add 1 to a for the one soda you can exchanging 3 empty cans. That is the issue. My above code addresses those issues\n",
"Here's a recursive approach:\ndef dr_cans(full, empty=0):\n # if we have at least 3 empty cans, exchange them for a full one\n if empty >=3:\n return dr_cans(full+1,empty-3)\n # no full cans, and not enough empty ones\n if full == 0:\n return 0\n # at least one full can: drink it and gain an empty one\n return 1 + dr_cans(full-1, empty+1)\n\n",
"If I understand corretly the question is as follows:\nLet k be the index of the exchange process. Since not all N can be divided by 3 we have N[k] = floor(M/3), where M=N[k-1]+R[k-1] new cans in each step. Plus some R[k] = M%3 leftover cans, where % is the modulo operator...\nWith this is should be quite easy...\ndef compute_num_cans(empty_cans: int, exchange: int = 3) -> tuple:\n \"\"\"\n :param empty_cans: The number of cans to exchange\n :return: tuple of (full_cans, empty_cans), where the empty cans are < exchange rate\n \"\"\"\n leftovers = empty_cans % exchange\n full = empty_cans // exchange\n return full, leftovers\n\n\nEXCHANGE = 3\nNUM_CANS = 51\n\nprint(f'Start with {NUM_CANS} and an exchange rate of {EXCHANGE}:1')\ncurrent_cans = NUM_CANS\ndrunk_cans = NUM_CANS\nleftovers = 0\nsteps = 0\nwhile current_cans >= EXCHANGE:\n full, leftovers = compute_num_cans(current_cans, exchange=EXCHANGE)\n current_cans = full + leftovers\n drunk_cans += full\n steps += 1\n\nprint(f'Cans drunk: {drunk_cans}, leftover cans: {leftovers}.')\nprint(f'A total of {steps} exchanges was needed.')\n\nThis yields as output\n# Start with 51 and an exchange rate of 3:1\n# Cans drunk: 76, leftover cans: 0.\n# A total of 4 exchanges was needed.\n\n",
"General Answer:- Accepted also if we change the numExchange also.\nCode:-\ndef numWaterBottles(numBottles: int, numExchange: int) -> int:\n ans=numBottles #Initial bottles he/she will drink\n while numBottles>=numExchange: #If numBottles<numExchange exit the while loop\n remainder=numBottles%numExchange #remaining bottles which is not change\n numBottles//=numExchange #The bottles which are changed\n ans+=numBottles #The bottles which are changed added to the answer\n numBottles+=remainder #Remaining bottles==The bottles which is not change+The bottles which are changed\n return ans #Return The answer\n \nprint(numWaterBottles(5,3))\nprint(numWaterBottles(100,3)) \nprint(numWaterBottles(32,4)) #numexchange when different\n\nOutput:-\n7\n149\n42\n\n"
] |
[
1,
1,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074582909_python.txt
|
Q:
pset 6 DNA, checking database for matching profiles
I am currently on pset 6 dna in cs50, I have completed the majoraty of the problem, but I can't seem to wrap my head round the final step, checking the database for matching profiles.
all of my code is located below to provide context for variables, I am unsure on the usage of my if loop and what I should be comparing, I think I may be overcompilcating it so any help with understanding or solving this problem would be appriciated
# TODO: Read database file into a variable
database = []
filename = sys.argv[1]
with open(filename) as f:
reader = csv.DictReader(f)
for row in reader:
database.append(row)
# TODO: Read DNA sequence file into a variable
sequence = []
filename = sys.argv[2]
with open(filename) as f:
r = f.read()
for column in r:
sequence.append(column)
# TODO: Find longest match of each STR in DNA sequence
subsequences = list(database[0].keys())[1:]
longest_sequence = {}
for subsequence in subsequences:
longest_sequence[subsequence] = longest_match(sequence, subsequence)
# TODO: Check database for matching profiles
databaselen = len(database)
sequencelen = len(sequence)
str_counts = [longest_sequence[subsequence]]
for i in range(databaselen):
for j in range(sequencelen):
if str_counts[j] == database[i][1:][j]:
print(database["name"])
return
A:
Before checking the database for matching profiles, you need to check your previous steps. When you do, you will find several problems:
First, sequence is not what you think it is. (You probably think
it is a string. Instead, it is a list of single character
strings.) This occurs because you create sequence as a string, and
are appending items to it.
Because of that error, longest_match() doesn't return the correct
counts for the subsequences. As a result, you have no chance to find
matches in the database.
The lesson: sometimes errors appear downstream from the real error. You need to check every line as you code.
Fix those errors, then work on the database match procedure. When you do, you will find additional errors.
You create variable str_counts which is the max count of any subsequence. That is not what you should be checking. You need to check the count for EVERY subsequence for each person against the database. (So, for sequence 1: {'AGATC': 4, 'AATG': 1, 'TATC': 5}).
Next, you are accessing elements of database incorrectly. database is a list of dictionaries (that uses keys). So, use list syntax to get each dictionary and dictionary syntax to get the key/value pairs.
Finally, you need to loop over each person and check their subsequence counts against the database. (Also, notice that STR values in database and longest_sequence are different types.) Procedure should look something like this. You need to add the details.
Code:
# database is a LIST of people DICTIONARIES
for person in database: # to loop on people in the list
# longest_sequence is a dictionary of STR:count values
for STR in longest_sequence:
# Check ALL longest_sequence[STR] values against all person[STR] values
# If ALL match, person is a match
# Otherwise, person is NOT a match
Good luck.
|
pset 6 DNA, checking database for matching profiles
|
I am currently on pset 6 dna in cs50, I have completed the majoraty of the problem, but I can't seem to wrap my head round the final step, checking the database for matching profiles.
all of my code is located below to provide context for variables, I am unsure on the usage of my if loop and what I should be comparing, I think I may be overcompilcating it so any help with understanding or solving this problem would be appriciated
# TODO: Read database file into a variable
database = []
filename = sys.argv[1]
with open(filename) as f:
reader = csv.DictReader(f)
for row in reader:
database.append(row)
# TODO: Read DNA sequence file into a variable
sequence = []
filename = sys.argv[2]
with open(filename) as f:
r = f.read()
for column in r:
sequence.append(column)
# TODO: Find longest match of each STR in DNA sequence
subsequences = list(database[0].keys())[1:]
longest_sequence = {}
for subsequence in subsequences:
longest_sequence[subsequence] = longest_match(sequence, subsequence)
# TODO: Check database for matching profiles
databaselen = len(database)
sequencelen = len(sequence)
str_counts = [longest_sequence[subsequence]]
for i in range(databaselen):
for j in range(sequencelen):
if str_counts[j] == database[i][1:][j]:
print(database["name"])
return
|
[
"Before checking the database for matching profiles, you need to check your previous steps. When you do, you will find several problems:\n\nFirst, sequence is not what you think it is. (You probably think\nit is a string. Instead, it is a list of single character\nstrings.) This occurs because you create sequence as a string, and\nare appending items to it.\nBecause of that error, longest_match() doesn't return the correct\ncounts for the subsequences. As a result, you have no chance to find\nmatches in the database.\n\nThe lesson: sometimes errors appear downstream from the real error. You need to check every line as you code.\nFix those errors, then work on the database match procedure. When you do, you will find additional errors.\n\nYou create variable str_counts which is the max count of any subsequence. That is not what you should be checking. You need to check the count for EVERY subsequence for each person against the database. (So, for sequence 1: {'AGATC': 4, 'AATG': 1, 'TATC': 5}).\nNext, you are accessing elements of database incorrectly. database is a list of dictionaries (that uses keys). So, use list syntax to get each dictionary and dictionary syntax to get the key/value pairs.\nFinally, you need to loop over each person and check their subsequence counts against the database. (Also, notice that STR values in database and longest_sequence are different types.) Procedure should look something like this. You need to add the details.\n\nCode:\n# database is a LIST of people DICTIONARIES\nfor person in database: # to loop on people in the list\n # longest_sequence is a dictionary of STR:count values\n for STR in longest_sequence: \n # Check ALL longest_sequence[STR] values against all person[STR] values\n # If ALL match, person is a match\n # Otherwise, person is NOT a match\n\nGood luck.\n"
] |
[
1
] |
[] |
[] |
[
"cs50",
"python"
] |
stackoverflow_0074577516_cs50_python.txt
|
Q:
How to make event.respond but just first sender will be responded? with Telethon
I have a question regarding the event on the telethon.
So, I want to make something like event.respond(). But only the first sender will be responded by the bot. If there is a second sender - and the rest are not responded to by bots.
How to make such a method? Thanks a lot for your answer. I use Telethon.
I've tried using the exit program method, it's not very effective. I have to restart the program to start it again. I want a method other than this, without having to restart the program.
A:
You can save the first sender somewhere and check it in subsequent events. One way to do it us using a global:
allowed_id = None
@client.on(events.NewMessage)
async def handler(event):
global allowed_id
if allowed_id is None:
allowed_id = event.sender_id
if event.sender_id == allowed_id:
await event.respond('allowed')
...
However, I would recommend to learn some more Python first.
|
How to make event.respond but just first sender will be responded? with Telethon
|
I have a question regarding the event on the telethon.
So, I want to make something like event.respond(). But only the first sender will be responded by the bot. If there is a second sender - and the rest are not responded to by bots.
How to make such a method? Thanks a lot for your answer. I use Telethon.
I've tried using the exit program method, it's not very effective. I have to restart the program to start it again. I want a method other than this, without having to restart the program.
|
[
"You can save the first sender somewhere and check it in subsequent events. One way to do it us using a global:\nallowed_id = None\n\n@client.on(events.NewMessage)\nasync def handler(event):\n global allowed_id\n if allowed_id is None:\n allowed_id = event.sender_id\n\n if event.sender_id == allowed_id:\n await event.respond('allowed')\n\n...\n\nHowever, I would recommend to learn some more Python first.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"python_telegram_bot",
"telegram",
"telethon"
] |
stackoverflow_0074579571_python_python_telegram_bot_telegram_telethon.txt
|
Q:
conda install spyder=5.3.3 stuck on solving env
I couldn't find much help on the internet, which is why I'm asking this here.
Spyder has an issue where input() will cause an issue to the app. I've heard that spyder 5.3.3 has this issue fixed.
I have done:
conda update conda
conda update anaconda
However, when I try conda install spyder=5.3.3, it says failed with initial frozen solve. Retrying with flexible solve.
It then never solves the environment. Any help?
A:
I tried all the solution posted but they does not work for my problem. I finally solved it by first uninstalling the existing spyder version and installing a new one. To do this, use this:
conda uninstall spyder
conda install spyder = 5.3.3
A:
I don't have a great solution, ran into the same issue myself, I was able to install version 5.2.2 where 5.1.5 is the base version. This version does also fix the input() problem you were having.
Alternatively you might try either of these two options to install spyder into it's own environment which should negate the problems but will require you to be in that environment to run spyder.
conda create -n spyder-env spyder
or
conda create -n spyder-env spyder numpy scipy pandas matplotlib sympy cython
A:
Close spyder. Run command: pip install --upgrade spyder
worked for me.
A:
Me as well. At least you could get it updated to 5.2.2 using the recommended update command from anaconda's page for spyder:
conda install -c anaconda spyder
Or use Vaxion's solution by creating an environment.
A:
I had the same problem, I tried on many ways. But this last worked for me:
conda install -c anaconda spyder
Maybe you can try it too.
I took it from anaconda / packages / spyder 5.3.3
A:
Probably your Environment is broken somehow. I suggest you to create a new environment specifying conda-forge as a channel already at creation time:
conda create -n spyder-env -c conda-forge python=3.10 spyder=5.3.3
The newest versions of Spyder are usually available on this channel. Then you can install your other packages and libraries there as well.
A:
Like others, the upgrade was advancing very slowly. It was not urgent, so I just left it, and it took about a week (!) and ended by barfing out 7000+ lines of package conflicts.
But then I followed the advice from Qiyuan Chen and it worked in just a few minutes:
conda uninstall spyder
conda install spyder=5.3.3
A:
Qiyuan Chen's answer also worked for me. After I uninstalled and reinstalled it, I went back to Anaconda Navigator and the Spyder icon was there with an install button underneath it. I hit 'INSTALL' and it worked.
|
conda install spyder=5.3.3 stuck on solving env
|
I couldn't find much help on the internet, which is why I'm asking this here.
Spyder has an issue where input() will cause an issue to the app. I've heard that spyder 5.3.3 has this issue fixed.
I have done:
conda update conda
conda update anaconda
However, when I try conda install spyder=5.3.3, it says failed with initial frozen solve. Retrying with flexible solve.
It then never solves the environment. Any help?
|
[
"I tried all the solution posted but they does not work for my problem. I finally solved it by first uninstalling the existing spyder version and installing a new one. To do this, use this:\nconda uninstall spyder\nconda install spyder = 5.3.3\n\n",
"I don't have a great solution, ran into the same issue myself, I was able to install version 5.2.2 where 5.1.5 is the base version. This version does also fix the input() problem you were having.\nAlternatively you might try either of these two options to install spyder into it's own environment which should negate the problems but will require you to be in that environment to run spyder.\nconda create -n spyder-env spyder\nor\nconda create -n spyder-env spyder numpy scipy pandas matplotlib sympy cython\n",
"Close spyder. Run command: pip install --upgrade spyder\nworked for me.\n",
"Me as well. At least you could get it updated to 5.2.2 using the recommended update command from anaconda's page for spyder:\nconda install -c anaconda spyder\n\nOr use Vaxion's solution by creating an environment.\n",
"I had the same problem, I tried on many ways. But this last worked for me:\nconda install -c anaconda spyder\n\nMaybe you can try it too.\nI took it from anaconda / packages / spyder 5.3.3\n",
"Probably your Environment is broken somehow. I suggest you to create a new environment specifying conda-forge as a channel already at creation time:\nconda create -n spyder-env -c conda-forge python=3.10 spyder=5.3.3\n\nThe newest versions of Spyder are usually available on this channel. Then you can install your other packages and libraries there as well.\n",
"Like others, the upgrade was advancing very slowly. It was not urgent, so I just left it, and it took about a week (!) and ended by barfing out 7000+ lines of package conflicts.\nBut then I followed the advice from Qiyuan Chen and it worked in just a few minutes:\nconda uninstall spyder\nconda install spyder=5.3.3\n\n",
"Qiyuan Chen's answer also worked for me. After I uninstalled and reinstalled it, I went back to Anaconda Navigator and the Spyder icon was there with an install button underneath it. I hit 'INSTALL' and it worked.\n"
] |
[
3,
0,
0,
0,
0,
0,
0,
0
] |
[] |
[] |
[
"anaconda",
"python"
] |
stackoverflow_0073874177_anaconda_python.txt
|
Q:
Python: Call function on each/any file in a module (dynamically)
I want to make a library of files, where each file does basically the same - solving math problems - but each implementation is slightly different. The way I want to set this up is as follows:
main.py (has a list of all problems, user can enter parameters)
solves\
prob001.py Problem, with definition of inputs, perhaps several different
solve() methods(solve_1(), solve_2() ...)
prob002.py 2nd Problem, structurally the same.
....
As I progress, more problemXX.py's will be added.
What code would I need to call solve_1 on prob002.py, and how do I make this as flexible/scalable as possible. Simply typing out import prob001 then prob001.solve(x, y) is not preferred, I want to generate menu's with options dynamically.
A:
Files: https://gist.github.com/thenarfer/330a4f978eab7c40e84e1dbaee062ebd
Check out the files for this script. Make sure to create the directory tree as follows:
math_solver_main.py
solves\
prob001.py
prob002.py
...
You can add more problems and the script will recognize it. I'm quite sure that this is not exactly what you are looking for, but possibly you can edit the contents of the problems and the execution of math_solver_main.py to your needs.
|
Python: Call function on each/any file in a module (dynamically)
|
I want to make a library of files, where each file does basically the same - solving math problems - but each implementation is slightly different. The way I want to set this up is as follows:
main.py (has a list of all problems, user can enter parameters)
solves\
prob001.py Problem, with definition of inputs, perhaps several different
solve() methods(solve_1(), solve_2() ...)
prob002.py 2nd Problem, structurally the same.
....
As I progress, more problemXX.py's will be added.
What code would I need to call solve_1 on prob002.py, and how do I make this as flexible/scalable as possible. Simply typing out import prob001 then prob001.solve(x, y) is not preferred, I want to generate menu's with options dynamically.
|
[
"Files: https://gist.github.com/thenarfer/330a4f978eab7c40e84e1dbaee062ebd\nCheck out the files for this script. Make sure to create the directory tree as follows:\nmath_solver_main.py \nsolves\\\n prob001.py \n prob002.py\n ...\n\n\n\nYou can add more problems and the script will recognize it. I'm quite sure that this is not exactly what you are looking for, but possibly you can edit the contents of the problems and the execution of math_solver_main.py to your needs.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0074581427_python_python_3.x.txt
|
Q:
How to define expected body of response containing list of indefinite number of JSON items in pytest?
I just started learning how to test API in python so please bear with me.
I want to test the endpoint that returns all users from database. My expected body looks like below:
[
{
"_id": "63811d56f6bea6b0dcb35342",
"email": "jan_kowalski@poczta.com",
"email_confirmed": "False",
"is_active": true,
"password": "12345",
"secret": "hdoofdgxksesdjvfrzsfedgqzouqnxyk",
"first_name": "Jan",
"last_name": "Kowalski",
"city": "Krakow",
"postal_code": "97-406",
"address": "ul. NMP 6"
},
{
"_id": "63811d6ef6bea6b0dcb35343",
"email": "adam_kowalski@poczta.com",
"email_confirmed": "False",
"is_active": true,
"password": "12345",
"secret": "vxnktmnsuflvloduewglwdtrgplccqoe",
"first_name": "Jan",
"last_name": "Kowalski",
"city": "Krakow",
"postal_code": "97-406",
"address": "ul. NMP 6"
}
]
Here is my test:
from app import main
def test_get_all_users(test_app):
response = test_app.get("/user/all")
assert response.status_code == 200
I should also add some checking if the resposne JSON is correct:
assert response.json() == {*my json*}
How to set assert response.json() to handle unknown number of JSON items?
A:
Without knowing the number of users that will be returned each time the test is run, the best you can do is check if each user in the response contains all the properties that are expected. Something like below:
from app import main
def test_get_all_users(test_app):
response = test_app.get("/user/all")
assert response.status_code == 200
users = response.json()
for user in users:
assert user["_id"]
assert user["email"]
assert user["email_confirmed"]
assert user["is_active"]
assert user["password"]
assert user["secret"]
assert user["first_name"]
assert user["last_name"]
assert user["city"]
assert user["postal_code"]
assert user["address"]
You could also check the types of the properties with assert type(user["_id"]) == str and so on.
However, the best test would be to have a known set of data which you can check when it is returned. To do that, if possible on your conditions, you could write a fixture that would create the database and then the users with certain properties so you could check their data later in a deterministic way and later destroy the database to have a fresh environment when the tests are run again.
|
How to define expected body of response containing list of indefinite number of JSON items in pytest?
|
I just started learning how to test API in python so please bear with me.
I want to test the endpoint that returns all users from database. My expected body looks like below:
[
{
"_id": "63811d56f6bea6b0dcb35342",
"email": "jan_kowalski@poczta.com",
"email_confirmed": "False",
"is_active": true,
"password": "12345",
"secret": "hdoofdgxksesdjvfrzsfedgqzouqnxyk",
"first_name": "Jan",
"last_name": "Kowalski",
"city": "Krakow",
"postal_code": "97-406",
"address": "ul. NMP 6"
},
{
"_id": "63811d6ef6bea6b0dcb35343",
"email": "adam_kowalski@poczta.com",
"email_confirmed": "False",
"is_active": true,
"password": "12345",
"secret": "vxnktmnsuflvloduewglwdtrgplccqoe",
"first_name": "Jan",
"last_name": "Kowalski",
"city": "Krakow",
"postal_code": "97-406",
"address": "ul. NMP 6"
}
]
Here is my test:
from app import main
def test_get_all_users(test_app):
response = test_app.get("/user/all")
assert response.status_code == 200
I should also add some checking if the resposne JSON is correct:
assert response.json() == {*my json*}
How to set assert response.json() to handle unknown number of JSON items?
|
[
"Without knowing the number of users that will be returned each time the test is run, the best you can do is check if each user in the response contains all the properties that are expected. Something like below:\nfrom app import main\n\ndef test_get_all_users(test_app):\n response = test_app.get(\"/user/all\")\n assert response.status_code == 200\n users = response.json()\n for user in users:\n assert user[\"_id\"]\n assert user[\"email\"]\n assert user[\"email_confirmed\"]\n assert user[\"is_active\"]\n assert user[\"password\"]\n assert user[\"secret\"]\n assert user[\"first_name\"]\n assert user[\"last_name\"]\n assert user[\"city\"]\n assert user[\"postal_code\"]\n assert user[\"address\"]\n\nYou could also check the types of the properties with assert type(user[\"_id\"]) == str and so on.\nHowever, the best test would be to have a known set of data which you can check when it is returned. To do that, if possible on your conditions, you could write a fixture that would create the database and then the users with certain properties so you could check their data later in a deterministic way and later destroy the database to have a fresh environment when the tests are run again.\n"
] |
[
1
] |
[] |
[] |
[
"pytest",
"python"
] |
stackoverflow_0074577727_pytest_python.txt
|
Q:
kivy + python: how to update form label based on external function response in multi-screen configuration
Hi to all kivy/python experts. I am looking for an advice/solution, after trying everything I found for the last week.
Here's my scenario:
I have a kivy app with 2 screens, therefore I am using a Screen manager, with each screen (1 and 2) defined in my .kv file
after clicking log-in on my 1st screen, app jumps to 2nd one. In this second screen, I have a button and a label (keeping it simple for the example). Now the issue:
when clicking on the button, I am calling a method foo1() which is in the same class: Screen2. foo1() is called on_press with a specific argument (from within .kv file, using on_press = root.foo1(arg))
based on the arg received, the function calculates something, then calls another function foo2(), passing the result. The foo2() is located in another python file(external.py), within another class (so we have different file, different class and in that class a method: foo2). All good so far
after finalizing some calculations, foo2() should return the result. Where? Well, inside my kivy label, on Screen2.
Problem encountered:
When trying to write the result from foo2() into my text label (my_label) in screenTwo, **foo2() **fails to instantiate the ids of the screen 2 (throwing all sorts of errors, depending on the things I tried (see below).
I can understand the reason: The moment I am calling foo2() from foo1() we are exiting the screenTwo as a parent for my_label, which changes the "self" context (of self.ids.my_label.text = result from foo2()). This now no longer refers to screenTwo, but probably to the in-memory address of the foo2() function which I think now acts as a parent (at least this is what I concluded, I am still a beginner in python).
Things I tried:
Basically everything I could find, to try and find the "real" parent that I need to enumerate, to find the children IDs where my_label actually is, but wasn't able to:
tried declaring an ObjectProperty = None inside my Screen2 class, then give an id to my label and then a variable name which refers to that id inside my Screen2 class. This is recommended by many tutorials, but this is working when passing things between screens, not in my case.
tried changing (inside foo2()) the reference to the destination of the label, from self.ids to
root.self.ids.my_label.text
root.manager.get_current('screenTwo').ids.my_label.text
main.root.manager.get_current('screenTwo').ids.my_label.text
app.main.root.manager.ids('screenTwo').ids.my_label.text
and maaaany other... :(
Depending on what I've tried (many tries) I received various errors. Here's some:
- kivy AttributeError: 'super' object has no attribute 'getattr' thread here also
- NameError: name 'root' is not defined
- AttributeError: 'str' object has no attribute 'text'
- Kivy AttributeError: 'NoneType' object has no attribute 'ids'
I do not seem to understand how this self/root/app context works, despite looking up at various resources (stackoverflow, pdf files, kivy official documentation) (if someone could recommend a good tutorial or explain for all newbies like me out there...wow how helpful it would be).
Also, I couldn't find anything related to whether this is actually possible, considering that from within the class that holds the current screen you're actually calling an external function located in another py file: **does kivy even support passing down responses from external functions back to the main function? **(I assume it does, since this is pure python, not kivy. kivy just manages the writing, within the correct context....if I were just able to figure it out :( ).
Anyway, here's my sample code (py + kv file). If any of you could give me a hint or a solution to how I could call a function which calls an external function which then writes the response back on the screen from which I started the events, in a label, I would be very thankful!
main.py
from kivy.uix.screenmanager import ScreenManager, Screen
from kivymd.app import MDApp
from kivy.app import App
from kivymd.uix.label import MDLabel
from kivy.properties import ObjectProperty, StringProperty
import external
class Screen1Main(Screen):
pass
class Screen2(Screen):
def foo1():
# 1. do something
myArg = "x"
# 2. then call foo2()
external.myExternalClass.foo2(myArg)
class WindowManager(ScreenManager):
pass
class MainApp(MDApp):
def __init__(self, **kwargs):
self.title = "My Application"
super().__init__(**kwargs)
if __name__ == "__main__":
MainApp().run()
external.py
from kivy.app import App
import main
class myExternalClass:
def foo2(arg1):
#1. does something
blabla
#2. gets the result
myResult = "anything"
#3. tries to write the result into my_label (located in Screen 2, which is a child
# of my main app (in file: main.py), who manages the multi-screen via a screen manager within
# WindowsManager class)
Screen2.manager.get_screen("screenTwo").ids.my_label.text = myResult
---
main.kv
WindowManager:
Screen1Main:
id: id_screenOne
Screen2:
id: id_screenTwo
<Screen1Main>:
name: "screenOne"
GridLayout:
<rest of layout here>
<Screen2>:
name: "screenTwo"
GridLayout:
cols: 2
MDLabel:
id: my_label
text: "-"
MDIconButton:
id: my_button
icon: "message-arrow-left"
on_release: root.foo1(arg0)
# Things I tried:
Basically everything I could find, as described above.
A:
I was not sure of the utility of having the separate class - but tried to give some examples here of passing information around. I think the key is to set up object references in your main App.
main.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from kivy.uix.screenmanager import ScreenManager, Screen
from kivymd.app import MDApp
from kivymd.uix.label import MDLabel
from kivymd.uix.textfield import MDTextField
from kivy.lang import Builder
class Screen1Main(Screen):
kv_text_field: MDTextField
class Screen2(Screen):
my_label: MDLabel
def __init__(self, **kwargs):
super().__init__(**kwargs)
class myExternalClass:
def foo2(self, arg):
self.myResult = "anything"
self._screen2.my_label.text = arg
def __init__(self, screen2):
self.myResult = ""
# get a reference to this screen so you can access it in this class instance
self._screen2: Screen2 = screen2
class WindowManager(ScreenManager):
pass
class MainApp(MDApp):
def foo1(self, my_button):
# 1. do something
myArg = "from main App"
print(f"{my_button}, {type(my_button)}")
# 2. then call foo2()
self.my_external_class.foo2(myArg)
def main_screen(self, my_button):
print(my_button)
self.my_top_widget.current = "Screen1Main"
def kv_change_screen(self, my_button, arg: str):
print(f"{self}, {my_button}, {arg}")
self.screen2.my_label.text = arg
self.my_top_widget.current = "Screen2"
def build(self) -> WindowManager:
self.my_top_widget.add_widget(self.screen1main)
self.my_top_widget.add_widget(self.screen2)
self.my_top_widget.current="Screen1Main"
return self.my_top_widget
def __init__(self, **kwargs):
self.title = "My Application"
super().__init__(**kwargs)
self.my_top_widget = WindowManager()
self.screen2 = Screen2(name="Screen2", )
self.screen1main = Screen1Main(name="Screen1Main")
self.screen1main.kv_text_field.text = "message to screen 2"
self.my_external_class = myExternalClass(screen2=self.screen2)
if __name__ == "__main__":
# load the file by name - this is more clear
Builder.load_file("main_app.kv")
my_app = MainApp()
my_app.run()
main_app.kv
#:import kivy kivy
# main_app.kv
<Screen1Main>:
kv_text_field: kv_text_field
MDBoxLayout:
orientation: 'vertical'
MDTextField:
id: kv_text_field
MDIconButton:
text: "button"
icon: "message-arrow-right"
on_press: app.kv_change_screen(self, kv_text_field.text)
<Screen2>:
my_label: my_label
GridLayout:
cols: 2
Label:
text: "Screen2"
MDLabel:
id: my_label
text: "-"
MDFlatButton:
id: my_button
text: "foo1"
on_release: app.foo1(self)
MDIconButton:
id: my_button
icon: "message-arrow-left"
on_release: app.main_screen(self)
you may not need your class definition WindowManager and you can directly use ScreenManager in place if you are not going to augment that class.
I hope the examples here can help you even if I didn't directly follow the exact flow and structure of your app.
A:
Try using:
MDApp.get_running_app().root.get_screen('screenTwo').ids.my_label.text = myResult
in your foo2() method. This gets the MDApp and references its root (the WindowManager) to get the the desired Screen.
|
kivy + python: how to update form label based on external function response in multi-screen configuration
|
Hi to all kivy/python experts. I am looking for an advice/solution, after trying everything I found for the last week.
Here's my scenario:
I have a kivy app with 2 screens, therefore I am using a Screen manager, with each screen (1 and 2) defined in my .kv file
after clicking log-in on my 1st screen, app jumps to 2nd one. In this second screen, I have a button and a label (keeping it simple for the example). Now the issue:
when clicking on the button, I am calling a method foo1() which is in the same class: Screen2. foo1() is called on_press with a specific argument (from within .kv file, using on_press = root.foo1(arg))
based on the arg received, the function calculates something, then calls another function foo2(), passing the result. The foo2() is located in another python file(external.py), within another class (so we have different file, different class and in that class a method: foo2). All good so far
after finalizing some calculations, foo2() should return the result. Where? Well, inside my kivy label, on Screen2.
Problem encountered:
When trying to write the result from foo2() into my text label (my_label) in screenTwo, **foo2() **fails to instantiate the ids of the screen 2 (throwing all sorts of errors, depending on the things I tried (see below).
I can understand the reason: The moment I am calling foo2() from foo1() we are exiting the screenTwo as a parent for my_label, which changes the "self" context (of self.ids.my_label.text = result from foo2()). This now no longer refers to screenTwo, but probably to the in-memory address of the foo2() function which I think now acts as a parent (at least this is what I concluded, I am still a beginner in python).
Things I tried:
Basically everything I could find, to try and find the "real" parent that I need to enumerate, to find the children IDs where my_label actually is, but wasn't able to:
tried declaring an ObjectProperty = None inside my Screen2 class, then give an id to my label and then a variable name which refers to that id inside my Screen2 class. This is recommended by many tutorials, but this is working when passing things between screens, not in my case.
tried changing (inside foo2()) the reference to the destination of the label, from self.ids to
root.self.ids.my_label.text
root.manager.get_current('screenTwo').ids.my_label.text
main.root.manager.get_current('screenTwo').ids.my_label.text
app.main.root.manager.ids('screenTwo').ids.my_label.text
and maaaany other... :(
Depending on what I've tried (many tries) I received various errors. Here's some:
- kivy AttributeError: 'super' object has no attribute 'getattr' thread here also
- NameError: name 'root' is not defined
- AttributeError: 'str' object has no attribute 'text'
- Kivy AttributeError: 'NoneType' object has no attribute 'ids'
I do not seem to understand how this self/root/app context works, despite looking up at various resources (stackoverflow, pdf files, kivy official documentation) (if someone could recommend a good tutorial or explain for all newbies like me out there...wow how helpful it would be).
Also, I couldn't find anything related to whether this is actually possible, considering that from within the class that holds the current screen you're actually calling an external function located in another py file: **does kivy even support passing down responses from external functions back to the main function? **(I assume it does, since this is pure python, not kivy. kivy just manages the writing, within the correct context....if I were just able to figure it out :( ).
Anyway, here's my sample code (py + kv file). If any of you could give me a hint or a solution to how I could call a function which calls an external function which then writes the response back on the screen from which I started the events, in a label, I would be very thankful!
main.py
from kivy.uix.screenmanager import ScreenManager, Screen
from kivymd.app import MDApp
from kivy.app import App
from kivymd.uix.label import MDLabel
from kivy.properties import ObjectProperty, StringProperty
import external
class Screen1Main(Screen):
pass
class Screen2(Screen):
def foo1():
# 1. do something
myArg = "x"
# 2. then call foo2()
external.myExternalClass.foo2(myArg)
class WindowManager(ScreenManager):
pass
class MainApp(MDApp):
def __init__(self, **kwargs):
self.title = "My Application"
super().__init__(**kwargs)
if __name__ == "__main__":
MainApp().run()
external.py
from kivy.app import App
import main
class myExternalClass:
def foo2(arg1):
#1. does something
blabla
#2. gets the result
myResult = "anything"
#3. tries to write the result into my_label (located in Screen 2, which is a child
# of my main app (in file: main.py), who manages the multi-screen via a screen manager within
# WindowsManager class)
Screen2.manager.get_screen("screenTwo").ids.my_label.text = myResult
---
main.kv
WindowManager:
Screen1Main:
id: id_screenOne
Screen2:
id: id_screenTwo
<Screen1Main>:
name: "screenOne"
GridLayout:
<rest of layout here>
<Screen2>:
name: "screenTwo"
GridLayout:
cols: 2
MDLabel:
id: my_label
text: "-"
MDIconButton:
id: my_button
icon: "message-arrow-left"
on_release: root.foo1(arg0)
# Things I tried:
Basically everything I could find, as described above.
|
[
"I was not sure of the utility of having the separate class - but tried to give some examples here of passing information around. I think the key is to set up object references in your main App.\nmain.py\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom kivy.uix.screenmanager import ScreenManager, Screen\nfrom kivymd.app import MDApp\nfrom kivymd.uix.label import MDLabel\nfrom kivymd.uix.textfield import MDTextField\nfrom kivy.lang import Builder\n\n\nclass Screen1Main(Screen):\n kv_text_field: MDTextField\n\n\nclass Screen2(Screen):\n my_label: MDLabel\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n\nclass myExternalClass:\n\n def foo2(self, arg):\n self.myResult = \"anything\"\n self._screen2.my_label.text = arg\n\n def __init__(self, screen2):\n self.myResult = \"\"\n # get a reference to this screen so you can access it in this class instance\n self._screen2: Screen2 = screen2\n\n\nclass WindowManager(ScreenManager):\n pass\n\n\nclass MainApp(MDApp):\n\n def foo1(self, my_button):\n # 1. do something\n myArg = \"from main App\"\n print(f\"{my_button}, {type(my_button)}\")\n\n # 2. then call foo2()\n self.my_external_class.foo2(myArg)\n\n def main_screen(self, my_button):\n print(my_button)\n self.my_top_widget.current = \"Screen1Main\"\n\n def kv_change_screen(self, my_button, arg: str):\n print(f\"{self}, {my_button}, {arg}\")\n self.screen2.my_label.text = arg\n self.my_top_widget.current = \"Screen2\"\n\n def build(self) -> WindowManager:\n\n self.my_top_widget.add_widget(self.screen1main)\n self.my_top_widget.add_widget(self.screen2)\n self.my_top_widget.current=\"Screen1Main\"\n return self.my_top_widget\n\n def __init__(self, **kwargs):\n self.title = \"My Application\"\n super().__init__(**kwargs)\n self.my_top_widget = WindowManager()\n self.screen2 = Screen2(name=\"Screen2\", )\n self.screen1main = Screen1Main(name=\"Screen1Main\")\n self.screen1main.kv_text_field.text = \"message to screen 2\"\n self.my_external_class = myExternalClass(screen2=self.screen2)\n\n\nif __name__ == \"__main__\":\n # load the file by name - this is more clear\n Builder.load_file(\"main_app.kv\")\n my_app = MainApp()\n my_app.run()\n\nmain_app.kv\n#:import kivy kivy\n# main_app.kv\n<Screen1Main>:\n kv_text_field: kv_text_field\n MDBoxLayout:\n orientation: 'vertical'\n MDTextField:\n id: kv_text_field\n MDIconButton:\n text: \"button\"\n icon: \"message-arrow-right\"\n on_press: app.kv_change_screen(self, kv_text_field.text)\n\n\n<Screen2>:\n my_label: my_label\n GridLayout:\n cols: 2\n Label:\n text: \"Screen2\"\n MDLabel:\n id: my_label\n text: \"-\"\n\n MDFlatButton:\n id: my_button\n text: \"foo1\"\n on_release: app.foo1(self)\n MDIconButton:\n id: my_button\n icon: \"message-arrow-left\"\n on_release: app.main_screen(self)\n\nyou may not need your class definition WindowManager and you can directly use ScreenManager in place if you are not going to augment that class.\nI hope the examples here can help you even if I didn't directly follow the exact flow and structure of your app.\n",
"Try using:\nMDApp.get_running_app().root.get_screen('screenTwo').ids.my_label.text = myResult\n\nin your foo2() method. This gets the MDApp and references its root (the WindowManager) to get the the desired Screen.\n"
] |
[
0,
0
] |
[] |
[] |
[
"kivy",
"kivy_language",
"kivymd",
"python",
"python_3.x"
] |
stackoverflow_0074582505_kivy_kivy_language_kivymd_python_python_3.x.txt
|
Q:
simplify python code - slice several lists and turn into tuple
I was wondering how to simplify the following python code. I tried to loop it but it didn't quite work out and I thought there must be a way without repeating the same thing over and over again.
coordinates = [
(9, 2, 17),
(4, 14, 11),
(8, 10, 6),
(2, 7, 0)
]
cdns = coordinates[0][0:2], coordinates[1][0:2], coordinates[2][0:2], coordinates[3][0:2]
newCnds = tuple(cdns)
newCnds
A:
You can use numpy:
>>> import numpy as np
>>> coordinates = [
... (9, 2, 17),
... (4, 14, 11),
... (8, 10, 6),
... (2, 7, 0)
... ]
>>> coordinates_np = np.array(coordinates)
>>> coordinates_np[:, 0:2]
array([[ 9, 2],
[ 4, 14],
[ 8, 10],
[ 2, 7]])
In general specifically for vectorized computation - numpy would be the best choice, both in terms of simplicity and speed.
A:
Use list comprehension
coordinates = [
(9, 2, 17),
(4, 14, 11),
(8, 10, 6),
(2, 7, 0)
]
newCnds = [i[:2] for i in coordinates]
|
simplify python code - slice several lists and turn into tuple
|
I was wondering how to simplify the following python code. I tried to loop it but it didn't quite work out and I thought there must be a way without repeating the same thing over and over again.
coordinates = [
(9, 2, 17),
(4, 14, 11),
(8, 10, 6),
(2, 7, 0)
]
cdns = coordinates[0][0:2], coordinates[1][0:2], coordinates[2][0:2], coordinates[3][0:2]
newCnds = tuple(cdns)
newCnds
|
[
"You can use numpy:\n>>> import numpy as np\n>>> coordinates = [\n... (9, 2, 17),\n... (4, 14, 11),\n... (8, 10, 6),\n... (2, 7, 0)\n... ]\n>>> coordinates_np = np.array(coordinates)\n>>> coordinates_np[:, 0:2]\narray([[ 9, 2],\n [ 4, 14],\n [ 8, 10],\n [ 2, 7]])\n\nIn general specifically for vectorized computation - numpy would be the best choice, both in terms of simplicity and speed.\n",
"Use list comprehension\ncoordinates = [\n (9, 2, 17),\n (4, 14, 11),\n (8, 10, 6),\n (2, 7, 0)\n]\nnewCnds = [i[:2] for i in coordinates]\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074583212_python.txt
|
Q:
Align LaTeX formula to text in Manim
I use the Poppins font for text and LaTeX for formulas (picture: number 1). The LaTeX text is vertically aligned higher than the Poppins text. I want both texts to be aligned on a horizontal line, like in (Image: number 2). How can I do that?
I use the function next_to() so that I can use the Poppins text and the LaTeX formula as continuous text. Is there perhaps a better way of creating continuous text using Poppins text and LaTeX formulas alternately?
Two types of text representation. Once with Poppins and LaTeX and once with LaTex only.
`
class ProofPowerSeries(Scene):
def construct(self):
definitionbn = Text("Sei", font="Poppins", color=BLACK, line_spacing=3).scale(0.5).to_edge(UL)
reason = MathTex(r"b_n := a_n(z-z_0)", color=BLACK).scale(0.75)
reason.next_to(definitionbn, buff=0.1)
latex = Tex("Sei $b_n := a_n(z-z_0)$", color=BLACK)
self.add(definitionbn, reason, latex)
`
I use the Text() function for text and MathTex() for formulas.
A:
The LaTeX-Schrift font aligns better if you use align_edge=UP in the next_to() function.
reason.next_to(definitionbn, aligned_edge=UP, buff=0.1)
|
Align LaTeX formula to text in Manim
|
I use the Poppins font for text and LaTeX for formulas (picture: number 1). The LaTeX text is vertically aligned higher than the Poppins text. I want both texts to be aligned on a horizontal line, like in (Image: number 2). How can I do that?
I use the function next_to() so that I can use the Poppins text and the LaTeX formula as continuous text. Is there perhaps a better way of creating continuous text using Poppins text and LaTeX formulas alternately?
Two types of text representation. Once with Poppins and LaTeX and once with LaTex only.
`
class ProofPowerSeries(Scene):
def construct(self):
definitionbn = Text("Sei", font="Poppins", color=BLACK, line_spacing=3).scale(0.5).to_edge(UL)
reason = MathTex(r"b_n := a_n(z-z_0)", color=BLACK).scale(0.75)
reason.next_to(definitionbn, buff=0.1)
latex = Tex("Sei $b_n := a_n(z-z_0)$", color=BLACK)
self.add(definitionbn, reason, latex)
`
I use the Text() function for text and MathTex() for formulas.
|
[
"The LaTeX-Schrift font aligns better if you use align_edge=UP in the next_to() function.\nreason.next_to(definitionbn, aligned_edge=UP, buff=0.1)\n\n"
] |
[
0
] |
[] |
[] |
[
"latex",
"manim",
"python",
"text"
] |
stackoverflow_0074576992_latex_manim_python_text.txt
|
Q:
(staticfiles.W004) The directory in the STATICFILES_DIRS setting does not exist error in django
so i am working on a project where i want to use some css files. but i couldn't link them with my html page in django. i've used everything i knew but still static is not loading
my error is:
(staticfiles.W004) The directory 'C:\Users\ASUS\PycharmProjects\e-payment\epayment\static' in the STATICFILES_DIRS setting does not exist.
my code snippets are given below:
my setting is:
settings.py
Django settings for epayment project.
Generated by 'django-admin startproject' using Django 4.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-+)&^ze^f+g#k28j#(1&r8y@u)g4=9!g7c4ef-i07!5@yhq2dd3'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'epayapp',
]
MIDDLEWARE = [
'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',
]
ROOT_URLCONF = 'epayment.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'epayment.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
here'e my base file that i am using
base.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title%} {% endblock %}</title>
<link rel="stylesheet" href="{% static '/epayapp/main.css'%}" type="text/css">
{% load static%}
<link rel="stylesheet" href="/static/common-styles.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
</head>
<style>
nav {
background-color: orange;
}
h2 {
font-family: "PT Serif";
}
h4 {
font-weight: 900;
}
#curr_bal {
border: 4px solid;
border-radius: 100px;
}
.current {
border: 1px solid;
padding: 3px;
}
.curr_bal {
font-family: "Cinzel";
font-weight: 600;
}
.col-sm-3
{
display: inline-block;
margin-left: -4px;
{% block css %} {% endblock %}
</style>
<body>
{% block body %}
{% endblock %}
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-u1OknCvxWvY5kfmNBILK2hRnQC3Pr17a+RTT6rIHI7NnikvbZlHgTPOOmMi466C8" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.min.js" integrity="sha384-7VPbUDkoPSGFnVtYi0QogXtr74QeVeeIs99Qfg5YCF+TidwNdjvaKZX19NZ/e6oz" crossorigin="anonymous"></script>
{% block script %} {% endblock %}
</body>
</html>
my css file that i want to link with
main.css
body {
background-color: floralwhite;
}
thanks in advance
A:
you need to simply create a folder with a name with which the error has caused, In simple words you need to create a folder named by static in your following path which is also shown in error itslef "(staticfiles.W004) The directory 'C:\Users\ASUS\PycharmProjects\e-payment\epayment\static' in the STATICFILES_DIRS setting does not exist.", the static folder is missing therefore the problem was invoked, i also had the same error "?: (staticfiles.W004) The directory '/home/mrnecro/dj_social/bffbook/static_project' in the STATICFILES_DIRS setting does not exist." so subsequently i did the same, i just created the the folder named by static_project and restarted the server again and the problem was gone!
Thankyou, hope this may help you, do comment if its not.
|
(staticfiles.W004) The directory in the STATICFILES_DIRS setting does not exist error in django
|
so i am working on a project where i want to use some css files. but i couldn't link them with my html page in django. i've used everything i knew but still static is not loading
my error is:
(staticfiles.W004) The directory 'C:\Users\ASUS\PycharmProjects\e-payment\epayment\static' in the STATICFILES_DIRS setting does not exist.
my code snippets are given below:
my setting is:
settings.py
Django settings for epayment project.
Generated by 'django-admin startproject' using Django 4.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-+)&^ze^f+g#k28j#(1&r8y@u)g4=9!g7c4ef-i07!5@yhq2dd3'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'epayapp',
]
MIDDLEWARE = [
'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',
]
ROOT_URLCONF = 'epayment.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'epayment.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
here'e my base file that i am using
base.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title%} {% endblock %}</title>
<link rel="stylesheet" href="{% static '/epayapp/main.css'%}" type="text/css">
{% load static%}
<link rel="stylesheet" href="/static/common-styles.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
</head>
<style>
nav {
background-color: orange;
}
h2 {
font-family: "PT Serif";
}
h4 {
font-weight: 900;
}
#curr_bal {
border: 4px solid;
border-radius: 100px;
}
.current {
border: 1px solid;
padding: 3px;
}
.curr_bal {
font-family: "Cinzel";
font-weight: 600;
}
.col-sm-3
{
display: inline-block;
margin-left: -4px;
{% block css %} {% endblock %}
</style>
<body>
{% block body %}
{% endblock %}
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-u1OknCvxWvY5kfmNBILK2hRnQC3Pr17a+RTT6rIHI7NnikvbZlHgTPOOmMi466C8" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.min.js" integrity="sha384-7VPbUDkoPSGFnVtYi0QogXtr74QeVeeIs99Qfg5YCF+TidwNdjvaKZX19NZ/e6oz" crossorigin="anonymous"></script>
{% block script %} {% endblock %}
</body>
</html>
my css file that i want to link with
main.css
body {
background-color: floralwhite;
}
thanks in advance
|
[
"you need to simply create a folder with a name with which the error has caused, In simple words you need to create a folder named by static in your following path which is also shown in error itslef \"(staticfiles.W004) The directory 'C:\\Users\\ASUS\\PycharmProjects\\e-payment\\epayment\\static' in the STATICFILES_DIRS setting does not exist.\", the static folder is missing therefore the problem was invoked, i also had the same error \"?: (staticfiles.W004) The directory '/home/mrnecro/dj_social/bffbook/static_project' in the STATICFILES_DIRS setting does not exist.\" so subsequently i did the same, i just created the the folder named by static_project and restarted the server again and the problem was gone!\nThankyou, hope this may help you, do comment if its not.\n"
] |
[
0
] |
[] |
[] |
[
"django",
"django_templates",
"python"
] |
stackoverflow_0074144591_django_django_templates_python.txt
|
Q:
How to convert text to list in python
input="""
intro: hey,how are you
i am fine
intro:
hey, how are you
Hope you are fine
"""
output= [['hey,how are you i am fine'],['hey, how are you Hope you are fine']]
for text in f:
text = text.strip()
A:
I would look into something like regex or just use
input.split("intro:") or input.splitlines() to generate a list of strings. That would not result in the form you have below. But since your question is not clear thats the best i can do.
A:
You could do this by splitting the input data by the string intro:. This will give you a list of the required items. You can clean this up a little more by removing the \n and leading/trailing spaces.
As an example:
data = """
intro: hey,how are you
i am fine
intro:
hey, how are you
Hope you are fine
"""
only_intro = []
for intro in data.split("intro:"):
if not intro.isspace():
only_intro.append(intro.replace('\n', ' ').lstrip().rstrip())
print(only_intro)
which gives the following output:
['hey,how are you i am fine', 'hey, how are you Hope you are fine']
|
How to convert text to list in python
|
input="""
intro: hey,how are you
i am fine
intro:
hey, how are you
Hope you are fine
"""
output= [['hey,how are you i am fine'],['hey, how are you Hope you are fine']]
for text in f:
text = text.strip()
|
[
"I would look into something like regex or just use\ninput.split(\"intro:\") or input.splitlines() to generate a list of strings. That would not result in the form you have below. But since your question is not clear thats the best i can do.\n",
"You could do this by splitting the input data by the string intro:. This will give you a list of the required items. You can clean this up a little more by removing the \\n and leading/trailing spaces.\nAs an example:\ndata = \"\"\"\nintro: hey,how are you\ni am fine\n\nintro:\nhey, how are you\nHope you are fine\n\"\"\"\nonly_intro = []\nfor intro in data.split(\"intro:\"):\n if not intro.isspace():\n only_intro.append(intro.replace('\\n', ' ').lstrip().rstrip())\nprint(only_intro)\n\nwhich gives the following output:\n['hey,how are you i am fine', 'hey, how are you Hope you are fine']\n\n"
] |
[
0,
0
] |
[
"We can use re.findall here in multiline mode:\ninp = \"\"\"intro: hey,how are you i am fine\n\nintro: hey, how are you Hope you are fine\"\"\"\n\nlines = re.findall(r'^\\w+:\\s*(.*)$', inp, flags=re.M)\nprint(lines)\n\nThis prints:\n['hey,how are you i am fine', 'hey, how are you Hope you are fine']\n\n"
] |
[
-1
] |
[
"file",
"list",
"logic",
"python",
"text"
] |
stackoverflow_0074582935_file_list_logic_python_text.txt
|
Q:
AttributeError: 'Grid' object has no attribute 'tk'
Who can help me to find this error , I will be thankful.
from tkinter import*
import math
root = Tk()
root.title("Jupiter Notebook Calculator")
root.resizable(width=False, height=False)
root.geometry("452x580+500+40")
mainFareme = Frame(root, bd=20, bg='gainsboro',relief=RIDGE)
mainFrame = Grid()
innerFareme = Frame(root, bd=10, bg='gainsboro',relief=RIDGE)
innerFrame = Grid()
class Calc():
def __init__(self):
self.total =0
self.current =""
self.firsnum=""
self.secondnum=""
self.input_value = True
self.check_sum=False
self.op=""
self.result=False
added_value = Calc()
txtDisplay = Entry(innerFrame, font=('arial',18,'bold'), bd=10, width=28, justify=RIGHT)
txtDisplay.grid (row=0, column=0, columnspan=4, pady=1)
txtDisplay.insert(0, "0")
numberpad = "789456123"
i = 0
btn = []
for j in range(3 , 6):
for k in range(3):
btn.append(Button(innerFrame, width=6, height =2,font=('arial',18,'bold'), bd=7, text= numberpad[i] ))
btn[i].grid(row=j,column = k, pady=1)
root.mainloop()
This is the error generated by the code:
Traceback (most recent call last):
File "/tmp/foo.py", line 28, in <module>
txtDisplay = Entry(innerFrame, font=('arial',18,'bold'), bd=10, width=28, justify=RIGHT)
File "/usr/local/Cellar/python@3.9/3.9.15/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 3035, in __init__
Widget.__init__(self, master, 'entry', cnf, kw)
File "/usr/local/Cellar/python@3.9/3.9.15/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 2566, in __init__
BaseWidget._setup(self, master, cnf)
File "/usr/local/Cellar/python@3.9/3.9.15/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 2535, in _setup
self.tk = master.tk
AttributeError: 'Grid' object has no attribute 'tk'
A:
mainFrame and innerFrame are an instance of Grid. An instance of Grid isn't a widget so you can't use it as the parent of another widget. A widget's parent (or master) must be a widget.
|
AttributeError: 'Grid' object has no attribute 'tk'
|
Who can help me to find this error , I will be thankful.
from tkinter import*
import math
root = Tk()
root.title("Jupiter Notebook Calculator")
root.resizable(width=False, height=False)
root.geometry("452x580+500+40")
mainFareme = Frame(root, bd=20, bg='gainsboro',relief=RIDGE)
mainFrame = Grid()
innerFareme = Frame(root, bd=10, bg='gainsboro',relief=RIDGE)
innerFrame = Grid()
class Calc():
def __init__(self):
self.total =0
self.current =""
self.firsnum=""
self.secondnum=""
self.input_value = True
self.check_sum=False
self.op=""
self.result=False
added_value = Calc()
txtDisplay = Entry(innerFrame, font=('arial',18,'bold'), bd=10, width=28, justify=RIGHT)
txtDisplay.grid (row=0, column=0, columnspan=4, pady=1)
txtDisplay.insert(0, "0")
numberpad = "789456123"
i = 0
btn = []
for j in range(3 , 6):
for k in range(3):
btn.append(Button(innerFrame, width=6, height =2,font=('arial',18,'bold'), bd=7, text= numberpad[i] ))
btn[i].grid(row=j,column = k, pady=1)
root.mainloop()
This is the error generated by the code:
Traceback (most recent call last):
File "/tmp/foo.py", line 28, in <module>
txtDisplay = Entry(innerFrame, font=('arial',18,'bold'), bd=10, width=28, justify=RIGHT)
File "/usr/local/Cellar/python@3.9/3.9.15/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 3035, in __init__
Widget.__init__(self, master, 'entry', cnf, kw)
File "/usr/local/Cellar/python@3.9/3.9.15/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 2566, in __init__
BaseWidget._setup(self, master, cnf)
File "/usr/local/Cellar/python@3.9/3.9.15/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 2535, in _setup
self.tk = master.tk
AttributeError: 'Grid' object has no attribute 'tk'
|
[
"mainFrame and innerFrame are an instance of Grid. An instance of Grid isn't a widget so you can't use it as the parent of another widget. A widget's parent (or master) must be a widget.\n"
] |
[
0
] |
[] |
[] |
[
"attributeerror",
"python",
"tkinter"
] |
stackoverflow_0074566971_attributeerror_python_tkinter.txt
|
Q:
Calculating Autocorrelation of Pandas DataFrame along each Column
I want to calculate the autocorrelation coefficients of lag length one among columns of a Pandas DataFrame. A snippet of my data is:
RF PC C D PN DN P
year
1890 NaN NaN NaN NaN NaN NaN NaN
1891 -0.028470 -0.052632 0.042254 0.081818 -0.045541 0.047619 -0.016974
1892 -0.249084 0.000000 0.027027 0.067227 0.099404 0.045455 0.122337
1893 0.653659 0.000000 0.000000 0.039370 -0.135624 0.043478 -0.142062
Along year, I want to calculate autocorrelations of lag one for each column (RF, PC, etc...).
To calculate the autocorrelations, I extracted two time series for each column whose start and end data differed by one year and then calculated correlation coefficients with numpy.corrcoef.
For example, I wrote:
numpy.corrcoef(data[['C']][1:-1],data[['C']][2:])
(the entire DataFrame is called data).
However, the command unfortunately returned:
array([[ nan, nan, nan, ..., nan, nan, nan],
[ nan, nan, nan, ..., nan, nan, nan],
[ nan, nan, nan, ..., nan, nan, nan],
...,
[ nan, nan, nan, ..., nan, nan, nan],
[ nan, nan, nan, ..., nan, nan, nan],
[ nan, nan, nan, ..., nan, nan, nan]])
Can somebody kindly advise me on how to calculate autocorrelations?
A:
This is a late answer, but for future users, you can also use the pandas.Series.autocorr(), which calculates lag-N (default=1) autocorrelation on Series:
df['C'].autocorr(lag=1)
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.autocorr.html#pandas.Series.autocorr
A:
.autocorr applies to Series, not DataFrames. You can use .apply to apply to a DataFrame:
def df_autocorr(df, lag=1, axis=0):
"""Compute full-sample column-wise autocorrelation for a DataFrame."""
return df.apply(lambda col: col.autocorr(lag), axis=axis)
d1 = DataFrame(np.random.randn(100, 6))
df_autocorr(d1)
Out[32]:
0 0.141
1 -0.028
2 -0.031
3 0.114
4 -0.121
5 0.060
dtype: float64
You could also compute rolling autocorrelations with a specified window as follows (this is what .autocorr is doing under the hood):
def df_rolling_autocorr(df, window, lag=1):
"""Compute rolling column-wise autocorrelation for a DataFrame."""
return (df.rolling(window=window)
.corr(df.shift(lag))) # could .dropna() here
df_rolling_autocorr(d1, window=21).dropna().head()
Out[38]:
0 1 2 3 4 5
21 -0.173 -0.367 0.142 -0.044 -0.080 0.012
22 0.015 -0.341 0.250 -0.036 0.023 -0.012
23 0.038 -0.329 0.279 -0.026 0.075 -0.121
24 -0.025 -0.361 0.319 0.117 0.031 -0.120
25 0.119 -0.320 0.181 -0.011 0.038 -0.111
A:
you should use:
numpy.corrcoef(df['C'][1:-1], df['C'][2:])
df[['C']] represents a dataframe with only one column, while df['C'] is a series containing the values in your C column.
A:
As I believe the use case where we need a window corresponding to highest correlation is more common, I have added another function which returns that window length per feature.
# Find autocorrelation example.
def df_autocorr(df, lag=1, axis=0):
"""Compute full-sample column-wise autocorrelation for a DataFrame."""
return df.apply(lambda col: col.autocorr(lag), axis=axis)
def df_rolling_autocorr(df, window, lag=1):
"""Compute rolling column-wise autocorrelation for a DataFrame."""
return (df.rolling(window=window)
.corr(df.shift(lag))) # could .dropna() here
def df_autocorr_highest(df, window_min, window_max, lag_f):
"""Returns a dictionary containing highest correlation coefficient wrt window length."""
df_corrs = pd.DataFrame()
df_corr_dict = {}
for i in range(len(df.columns)):
corr_init = 0
corr_index = 0
for j in range(window_min, window_max):
corr = df_rolling_autocorr(df.iloc[:,i], window=j, lag=lag_f).dropna().mean()
if corr > corr_init:
corr_init = corr
corr_index = j
corr_label = df.columns[i] + "_corr"
df_corr_dict[corr_label] = [corr_init, corr_index]
return df_corr_dict
|
Calculating Autocorrelation of Pandas DataFrame along each Column
|
I want to calculate the autocorrelation coefficients of lag length one among columns of a Pandas DataFrame. A snippet of my data is:
RF PC C D PN DN P
year
1890 NaN NaN NaN NaN NaN NaN NaN
1891 -0.028470 -0.052632 0.042254 0.081818 -0.045541 0.047619 -0.016974
1892 -0.249084 0.000000 0.027027 0.067227 0.099404 0.045455 0.122337
1893 0.653659 0.000000 0.000000 0.039370 -0.135624 0.043478 -0.142062
Along year, I want to calculate autocorrelations of lag one for each column (RF, PC, etc...).
To calculate the autocorrelations, I extracted two time series for each column whose start and end data differed by one year and then calculated correlation coefficients with numpy.corrcoef.
For example, I wrote:
numpy.corrcoef(data[['C']][1:-1],data[['C']][2:])
(the entire DataFrame is called data).
However, the command unfortunately returned:
array([[ nan, nan, nan, ..., nan, nan, nan],
[ nan, nan, nan, ..., nan, nan, nan],
[ nan, nan, nan, ..., nan, nan, nan],
...,
[ nan, nan, nan, ..., nan, nan, nan],
[ nan, nan, nan, ..., nan, nan, nan],
[ nan, nan, nan, ..., nan, nan, nan]])
Can somebody kindly advise me on how to calculate autocorrelations?
|
[
"This is a late answer, but for future users, you can also use the pandas.Series.autocorr(), which calculates lag-N (default=1) autocorrelation on Series:\ndf['C'].autocorr(lag=1)\n\nhttp://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.autocorr.html#pandas.Series.autocorr\n",
".autocorr applies to Series, not DataFrames. You can use .apply to apply to a DataFrame:\ndef df_autocorr(df, lag=1, axis=0):\n \"\"\"Compute full-sample column-wise autocorrelation for a DataFrame.\"\"\"\n return df.apply(lambda col: col.autocorr(lag), axis=axis)\nd1 = DataFrame(np.random.randn(100, 6))\n\ndf_autocorr(d1)\nOut[32]: \n0 0.141\n1 -0.028\n2 -0.031\n3 0.114\n4 -0.121\n5 0.060\ndtype: float64\n\nYou could also compute rolling autocorrelations with a specified window as follows (this is what .autocorr is doing under the hood):\ndef df_rolling_autocorr(df, window, lag=1):\n \"\"\"Compute rolling column-wise autocorrelation for a DataFrame.\"\"\"\n\n return (df.rolling(window=window)\n .corr(df.shift(lag))) # could .dropna() here\n\ndf_rolling_autocorr(d1, window=21).dropna().head()\nOut[38]: \n 0 1 2 3 4 5\n21 -0.173 -0.367 0.142 -0.044 -0.080 0.012\n22 0.015 -0.341 0.250 -0.036 0.023 -0.012\n23 0.038 -0.329 0.279 -0.026 0.075 -0.121\n24 -0.025 -0.361 0.319 0.117 0.031 -0.120\n25 0.119 -0.320 0.181 -0.011 0.038 -0.111\n\n",
"you should use:\nnumpy.corrcoef(df['C'][1:-1], df['C'][2:])\n\ndf[['C']] represents a dataframe with only one column, while df['C'] is a series containing the values in your C column.\n",
"As I believe the use case where we need a window corresponding to highest correlation is more common, I have added another function which returns that window length per feature.\n# Find autocorrelation example.\ndef df_autocorr(df, lag=1, axis=0):\n \"\"\"Compute full-sample column-wise autocorrelation for a DataFrame.\"\"\"\n return df.apply(lambda col: col.autocorr(lag), axis=axis)\n\ndef df_rolling_autocorr(df, window, lag=1):\n \"\"\"Compute rolling column-wise autocorrelation for a DataFrame.\"\"\"\n\n return (df.rolling(window=window)\n .corr(df.shift(lag))) # could .dropna() here\n\ndef df_autocorr_highest(df, window_min, window_max, lag_f):\n \"\"\"Returns a dictionary containing highest correlation coefficient wrt window length.\"\"\"\n df_corrs = pd.DataFrame()\n df_corr_dict = {}\n for i in range(len(df.columns)):\n corr_init = 0\n corr_index = 0\n for j in range(window_min, window_max): \n corr = df_rolling_autocorr(df.iloc[:,i], window=j, lag=lag_f).dropna().mean()\n if corr > corr_init:\n corr_init = corr\n corr_index = j\n corr_label = df.columns[i] + \"_corr\" \n df_corr_dict[corr_label] = [corr_init, corr_index]\n return df_corr_dict\n\n"
] |
[
22,
15,
4,
0
] |
[] |
[] |
[
"numpy",
"pandas",
"python"
] |
stackoverflow_0026083293_numpy_pandas_python.txt
|
Q:
How do I get rid of the "{}" in my windows output? (Python / SQLite3)
I'm creating a flashcard game to ask CompSci questions.
I'm trying to retrieve a random "CardFront" which acts as a varchar stored in an SQLite3 DB table, and output that result to a messagebox to "Prompt" the user with the question.
Only problem I can't seem to figure out is why it is returning with squiggly brackets around the statement?
from tkinter import *
import sqlite3
from tkinter import messagebox
def retrieve_random_cardfront():
conn = sqlite3.connect('flashcards.db')
cursor = conn.cursor()
cursor.execute("SELECT CardFront FROM FLASHCARDS ORDER BY RANDOM() LIMIT 1;")
result = cursor.fetchall()
conn.close()
messagebox.showinfo(title='Test', message=result[0])
Current Output
A:
I think you can implement something like this in order to remove that "{}". But since I'm not aware of using SQLite, I could give you a more precise answer.
data = "{Data}"
data = data.replace(data[0], "")
data = data.replace(data[-1], "")
print(data)
A:
tkinter will add curly braces when it expects a string but you pass a list. The proper solution is to convert your list to a string before using it with a widget. The following example shows once possible way:
message = ",".join(result[0])
messagebox.showinfo(title='Test', message=message)
A:
You can try this as a fix, but what is happening is unclear here. Maybe check into the __repr__ of the result object ?
from tkinter import *
import sqlite3
from tkinter import messagebox
def retrieve_random_cardfront():
conn = sqlite3.connect('flashcards.db')
cursor = conn.cursor()
cursor.execute("SELECT CardFront FROM FLASHCARDS ORDER BY RANDOM() LIMIT 1;")
result = cursor.fetchall()
conn.close()
messagebox.showinfo(title='Test', message=str(result[0]).strip('{').strip('}'))
|
How do I get rid of the "{}" in my windows output? (Python / SQLite3)
|
I'm creating a flashcard game to ask CompSci questions.
I'm trying to retrieve a random "CardFront" which acts as a varchar stored in an SQLite3 DB table, and output that result to a messagebox to "Prompt" the user with the question.
Only problem I can't seem to figure out is why it is returning with squiggly brackets around the statement?
from tkinter import *
import sqlite3
from tkinter import messagebox
def retrieve_random_cardfront():
conn = sqlite3.connect('flashcards.db')
cursor = conn.cursor()
cursor.execute("SELECT CardFront FROM FLASHCARDS ORDER BY RANDOM() LIMIT 1;")
result = cursor.fetchall()
conn.close()
messagebox.showinfo(title='Test', message=result[0])
Current Output
|
[
"I think you can implement something like this in order to remove that \"{}\". But since I'm not aware of using SQLite, I could give you a more precise answer.\ndata = \"{Data}\"\ndata = data.replace(data[0], \"\")\ndata = data.replace(data[-1], \"\")\nprint(data)\n\n",
"tkinter will add curly braces when it expects a string but you pass a list. The proper solution is to convert your list to a string before using it with a widget. The following example shows once possible way:\nmessage = \",\".join(result[0])\nmessagebox.showinfo(title='Test', message=message)\n\n",
"You can try this as a fix, but what is happening is unclear here. Maybe check into the __repr__ of the result object ?\nfrom tkinter import *\nimport sqlite3\nfrom tkinter import messagebox\n\ndef retrieve_random_cardfront():\n conn = sqlite3.connect('flashcards.db')\n cursor = conn.cursor()\n cursor.execute(\"SELECT CardFront FROM FLASHCARDS ORDER BY RANDOM() LIMIT 1;\")\n result = cursor.fetchall()\n conn.close()\n messagebox.showinfo(title='Test', message=str(result[0]).strip('{').strip('}'))\n\n"
] |
[
0,
0,
-1
] |
[] |
[] |
[
"python",
"sqlite"
] |
stackoverflow_0074555272_python_sqlite.txt
|
Q:
Count value column iteratively for rows within column
I have a dataframe that looks like this:
info_version commits commitdates
18558 17.1.3 42 2017-07-14
20783 17.1.3 57 2017-07-14
20782 17.2.2 57 2017-09-27
18557 17.2.2 42 2017-09-27
18556 17.2.3 42 2017-10-30
20781 17.2.3 57 2017-10-30
20780 17.2.4 57 2017-11-27
18555 17.2.4 42 2017-11-27
20779 17.2.5 57 2018-01-10
I have a trivial issue, but somehow I am not able to find the function,I want to count the commits starting from value 42 till the last one, my desired output is something like this:
info_version commits commitdates Commit_growth
18558 17.1.3 42 2017-07-14 42
20783 17.1.3 57 2017-07-14 109
20782 17.2.2 57 2017-09-27 166
18557 17.2.2 42 2017-09-27. 208
18556 17.2.3 42 2017-10-30 250
20781 17.2.3 57 2017-10-30 307
20780 17.2.4 57 2017-11-27 364
18555 17.2.4 42 2017-11-27. 406
20779 17.2.5 57 2018-01-10 463
This is what I tried so far:
data2 = data1[['info_version', 'commits', 'commitdates']].sort_values(by='info_version', ascending=True)
sum_row = data2.sum(axis=0)
But this gives me the entire count. This seems to be easy, but I am a bit stuck.
A:
You can use sort_values with cumsum but the output is different from yours :
data1["commitdates"]= pd.to_datetime(data1["commitdates"]) #only if not parsed yet
data2= (
data1
.loc[:, ["info_version", "commits", "commitdates"]]
.sort_values(by=["info_version", "commitdates"])
.assign(Commit_growth= lambda x: x["commits"].cumsum())
)
# Output :
print(data2)
info_version commits commitdates Commit_growth
18558 17.1.3 42 2017-07-14 42
20783 17.1.3 57 2017-07-14 99
20782 17.2.2 57 2017-09-27 156
18557 17.2.2 42 2017-09-27 198
18556 17.2.3 42 2017-10-30 240
20781 17.2.3 57 2017-10-30 297
20780 17.2.4 57 2017-11-27 354
18555 17.2.4 42 2017-11-27 396
20779 17.2.5 57 2018-01-10 453
A:
A simple .cumsum() should be suffice,
because it looks like the df is already sorted by info_version
data1['Commit_growth'] = data1['commits'].cumsum()
Here is the example code:
import pandas as pd
data1 = pd.DataFrame({ 'info_version': ['17.1.3', '17.1.3', '17.2.2', '17.2.2', '17.2.3', '17.2.3', '17.2.4', '17.2.4', '17.2.5'],
'commits': [42, 57, 57, 42, 42, 57, 57, 42, 57],
'commitdates': ['2017-07-14', '2017-07-14', '2017-09-27', '2017-09-27', '2017-10-30', '2017-10-30', '2017-11-27', '2017-11-27', '2018-01-10']})
data1['Commit_growth'] = data1['commits'].cumsum()
print(data1)
OUTPUT:
info_version commits commitdates Commit_growth
0 17.1.3 42 2017-07-14 42
1 17.1.3 57 2017-07-14 99
2 17.2.2 57 2017-09-27 156
3 17.2.2 42 2017-09-27 198
4 17.2.3 42 2017-10-30 240
5 17.2.3 57 2017-10-30 297
6 17.2.4 57 2017-11-27 354
7 17.2.4 42 2017-11-27 396
8 17.2.5 57 2018-01-10 453
|
Count value column iteratively for rows within column
|
I have a dataframe that looks like this:
info_version commits commitdates
18558 17.1.3 42 2017-07-14
20783 17.1.3 57 2017-07-14
20782 17.2.2 57 2017-09-27
18557 17.2.2 42 2017-09-27
18556 17.2.3 42 2017-10-30
20781 17.2.3 57 2017-10-30
20780 17.2.4 57 2017-11-27
18555 17.2.4 42 2017-11-27
20779 17.2.5 57 2018-01-10
I have a trivial issue, but somehow I am not able to find the function,I want to count the commits starting from value 42 till the last one, my desired output is something like this:
info_version commits commitdates Commit_growth
18558 17.1.3 42 2017-07-14 42
20783 17.1.3 57 2017-07-14 109
20782 17.2.2 57 2017-09-27 166
18557 17.2.2 42 2017-09-27. 208
18556 17.2.3 42 2017-10-30 250
20781 17.2.3 57 2017-10-30 307
20780 17.2.4 57 2017-11-27 364
18555 17.2.4 42 2017-11-27. 406
20779 17.2.5 57 2018-01-10 463
This is what I tried so far:
data2 = data1[['info_version', 'commits', 'commitdates']].sort_values(by='info_version', ascending=True)
sum_row = data2.sum(axis=0)
But this gives me the entire count. This seems to be easy, but I am a bit stuck.
|
[
"You can use sort_values with cumsum but the output is different from yours :\ndata1[\"commitdates\"]= pd.to_datetime(data1[\"commitdates\"]) #only if not parsed yet\n\ndata2= (\n data1\n .loc[:, [\"info_version\", \"commits\", \"commitdates\"]]\n .sort_values(by=[\"info_version\", \"commitdates\"])\n .assign(Commit_growth= lambda x: x[\"commits\"].cumsum())\n )\n\n# Output :\nprint(data2)\n\n info_version commits commitdates Commit_growth\n 18558 17.1.3 42 2017-07-14 42\n 20783 17.1.3 57 2017-07-14 99\n 20782 17.2.2 57 2017-09-27 156\n 18557 17.2.2 42 2017-09-27 198\n 18556 17.2.3 42 2017-10-30 240\n 20781 17.2.3 57 2017-10-30 297\n 20780 17.2.4 57 2017-11-27 354\n 18555 17.2.4 42 2017-11-27 396\n 20779 17.2.5 57 2018-01-10 453\n\n",
"A simple .cumsum() should be suffice, \nbecause it looks like the df is already sorted by info_version\ndata1['Commit_growth'] = data1['commits'].cumsum()\n\n\n\nHere is the example code:\nimport pandas as pd\n\ndata1 = pd.DataFrame({ 'info_version': ['17.1.3', '17.1.3', '17.2.2', '17.2.2', '17.2.3', '17.2.3', '17.2.4', '17.2.4', '17.2.5'],\n 'commits': [42, 57, 57, 42, 42, 57, 57, 42, 57],\n 'commitdates': ['2017-07-14', '2017-07-14', '2017-09-27', '2017-09-27', '2017-10-30', '2017-10-30', '2017-11-27', '2017-11-27', '2018-01-10']})\n\ndata1['Commit_growth'] = data1['commits'].cumsum()\nprint(data1)\n\nOUTPUT:\n info_version commits commitdates Commit_growth\n0 17.1.3 42 2017-07-14 42\n1 17.1.3 57 2017-07-14 99\n2 17.2.2 57 2017-09-27 156\n3 17.2.2 42 2017-09-27 198\n4 17.2.3 42 2017-10-30 240\n5 17.2.3 57 2017-10-30 297\n6 17.2.4 57 2017-11-27 354\n7 17.2.4 42 2017-11-27 396\n8 17.2.5 57 2018-01-10 453\n\n"
] |
[
2,
2
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074583244_pandas_python.txt
|
Q:
why my function don't return the last value?
I have written class called Atoms and I put inside it, in short, all the information you need in order to work on distributing the electrons of some atoms, and I put it in a dictionary dict, its symbol is the key and its atomic number is the value, and I made a set of conditional sentences in order to distribute the atoms and put them inside a list, but it excludes the last value and Don't put it on the list.
This is my code:
class Atoms:
def __init__(self, protons, neutrons, electrons):
self.protons = protons
self.neutrons = neutrons
self.electrons = electrons
def atoms_info(the_atom_name):
global Atoms_info
global Atomic_Number
Atoms_info = {"H": ("Hydrogen", "Atomic Number : 1"), "He": ("Helium", "Atomic Number : 2"), "Li": ("Lithium", "Atomic Number : 3"),"Be": ("Beryllium", "Atomic Number : 4"),
"B": ("Boron", "Atomic Number : 5"),"C": ("Carbon", "Atomic Number : 6"), "N": ("Nitrogen", "Atomic Number : 7"),"O": ("Oxygen", "Atomic Number : 8"),
"F": ("Fluorine", "Atomic Number : 9"), "Ne": ("Neon", "Atomic Number : 10"), "Na": ("Sodium", "Atomic Number : 11"), "Mg": ("Magnesium", "Atomic Number : 12"),
"Al": ("Aluminium", "Atomic Number : 13"), "Si": ("Silicon", "Atomic Number : 14"), "P": ("Phosphorus", "Atomic Number : 15"), "S": ("Sulfur", "Atomic Number : 16"),
"Cl": ("Chlorine", "Atomic Number : 17"), "Ar": ("Argon", "Atomic Number : 18"), "K": ("Potassium", "Atomic Number : 19"), "Ca": ("Calcium", "Atomic Number : 20"),
"Sc": ("Scandium", "Atomic Number : 21"), "Ti": ("Titanium", "Atomic Number : 22"), "V": ("Vanadium", "Atomic Number : 23"), "Cr": ("Chromium", "Atomic Number : 24"),
"Mn": ("Manganese", "Atomic Number : 25"), "Fe": ("Iron", "Atomic Number : 26"), "Co": ("Cobalt", "Atomic Number : 27"), "Ni": ("Nickel", "Atomic Number : 28"),
"Cu": ("Copper", "Atomic Number : 29"), "Zn": ("Zinc", "Atomic Number : 30"), "Ga": ("Gallium", "Atomic Number : 31"), "Ge": ("Germanium", "Atomic Number : 32"),
"As": ("Arsenic", "Atomic Number : 33"), "Se": ("Selenium", "Atomic Number : 34"), "Br": ("Bromine", "Atomic Number : 35"), "Kr": ("Krypton", "Atomic Number : 36"),
"Rb": ("Rubidium", "Atomic Number : 37"), "Sr": ("Strontium", "Atomic Number : 38"), "Y": ("Yttrium", "Atomic Number : 39"), "Zr": ("Zirconium", "Atomic Number : 40"),
"Nb": ("Niobium", "Atomic Number : 41"), "Mo": ("Molybdenum", "Atomic Number : 42"), "Tc": ("Technetium", "Atomic Number : 43"), "Ru": ("Ruthenium", "Atomic Number : 44"),
"Rh": ("Rhodium", "Atomic Number : 45"), "Pd": ("Palladium", "Atomic Number : 46"), "Ag": ("Silver", "Atomic Number : 47"), "Cd": ("Cadmium", "Atomic Number : 48"),
"In": ("Indium", "Atomic Number : 49"), "Sn": ("Tin", "Atomic Number : 50"), "Sb": ("Antimony", "Atomic Number : 51"), "Te": ("Tellurium", "Atomic Number : 52"),
"I": ("Iodine", "Atomic Number : 53"), "Xe": ("Xenon", "Atomic Number : 54"), "Cs": ("Caesium", "Atomic Number : 55"), "Ba": ("Barium", "Atomic Number : 56"),
"La": ("Lanthanum", "Atomic Number : 57"), "Ce": ("Cerium", "Atomic Number : 58"), "Pr": ("Praseodymium", "Atomic Number : 59"), "Nd": ("Neodymium", "Atomic Number : 60"),
"Pm": ("Promethium", "Atomic Number : 61"), "Sm": ("Samarium", "Atomic Number : 62"), "Eu": ("Europium", "Atomic Number : 63"), "Gd": ("Gadolinium", "Atomic Number : 64"),
"Tb": ("Terbium", "Atomic Number : 65"), "Dy": ("Dysprosium", "Atomic Number : 66"), "Ho": ("Holmium", "Atomic Number : 67"), "Er": ("Erbium", "Atomic Number : 68"),
"Tm": ("Thulium", "Atomic Number : 69"), "Yb": ("Ytterbium", "Atomic Number : 70"), "Lu": ("Lutetium", "Atomic Number : 71"), "Hf": ("Hafnium", "Atomic Number : 72"),
"Ta": ("Tantalum", "Atomic Number : 73"), "W": ("Tungsten", "Atomic Number : 74"), "Re": ("Rhenium", "Atomic Number : 75"), "Os": ("Osmium", "Atomic Number : 76"),
"Ir": ("Iridium", "Atomic Number : 77"), "Pt": ("Platinum", "Atomic Number : 78"), "Au": ("Gold", "Atomic Number : 79"), "Hg": ("Mercury", "Atomic Number : 80"),
"Tl": ("Thallium", "Atomic Number : 81"), "Pb": ("Lead", "Atomic Number : 82"), "Bi": ("Bismuth", "Atomic Number : 83"), "Po": ("Polonium", "Atomic Number : 84"),
"At": ("Astatine", "Atomic Number : 85"), "Rn": ("Radon", "Atomic Number : 86"), "Fr": ("Francium", "Atomic Number : 87"), "Ra": ("Radium", "Atomic Number : 88"),
"Ac": ("Actinium", "Atomic Number : 89"), "Th": ("Thorium", "Atomic Number : 90"), "Pa": ("Protactinium", "Atomic Number : 91"), "U": ("Uranium", "Atomic Number : 92"),
"Np": ("Neptunium", "Atomic Number : 93"), "Pu": ("Plutonium", "Atomic Number : 94"), "Am": ("Americium", "Atomic Number : 95"), "Cm": ("Curium", "Atomic Number : 96"),
"Bk": ("Berkelium", "Atomic Number : 97"), "Cf": ("Californium", "Atomic Number : 98"), "Es": ("Einsteinium", "Atomic Number : 99"), "Fm": ("Fermium", "Atomic Number : 100"),
"Md": ("Mendelevium", "Atomic Number : bitcoin101"), "No": ("Nobelium", "Atomic Number : 102"), "Lr": ("Lawrencium", "Atomic Number : 103"), "Rf": ("Rutherfordium", "Atomic Number : 104"),
"Db": ("Dubnium", "Atomic Number : 105"), "Sg": ("Seaborgium", "Atomic Number : 106"), "Bh": ("Bohrium", "Atomic Number : 107"), "Hs": ("Hassium", "Atomic Number : 108"),
"Mt": ("Meitnerium", "Atomic Number : 109"), "Ds": ("Darmstadtium", "Atomic Number : 110"), "Rg": ("Roentgenium", "Atomic Number : 111"), "Cn": ("Copernicium", "Atomic Number : 112"),
"Nh": ("Nihonium", "Atomic Number : 113"), "Fl": ("Flerovium", "Atomic Number : 114"), "Mc": ("Moscovium", "Atomic Number : 115"), "Lv": ("Livermorium", "Atomic Number : 116"),
"Ts": ("Tennessine", "Atomic Number : 117"), "Og": ("Oganesson", "Atomic Number : 118")}
if the_atom_name == 'all_info':
for key, value in Atoms_info.items():
print(key, value)
elif the_atom_name == 'symbol':
temp = 1
for key in Atoms_info:
print(f'Key_{temp} : {key}')
temp += 1
else:
print(Atoms_info.get(the_atom_name, 'No atom has this symbol'))
Atomic_Number = {"H": 1, "He": 2, "Li": 3, "Be": 4, "B": 5, "C": 6, "N": 7, "O": 8, "F": 9, "Ne": 10,
"Na": 11, "Mg": 12, "Al": 13, "Si": 14, "P": 15, "S": 16, "Cl": 17, "Ar": 18, "K": 19, "Ca": 20,"Sc": 21, "Ti": 22,
"V": 23, "Cr": 24, "Mn": 25, "Fe": 26, "Co": 27, "Ni": 28, "Cu": 29, "Zn": 30, "Ga": 31, "Ge": 32, "As": 33, "Se": 34,
"Br": 35, "Kr": 36, "Rb": 37, "Sr": 38,"Y": 39, "Zr": 40, "Nb": 41, "Mo": 42, "Tc": 43, "Ru": 44, "Rh": 45, "Pd": 46,
"Ag": 47,"Cd": 48, "In": 49, "Sn": 50, "Sb": 51, "Te": 52, "I": 53, "Xe": 54, "Cs": 55, "Ba": 56, "La": 57, "Ce": 58,
"Pr": 59,"Nd": 60, "Pm": 61, "Sm": 62, "Eu": 63, "Gd": 64, "Tb": 65, "Dy": 66, "Ho": 67, "Er": 68, "Tm": 69, "Yb": 70,
"Lu": 71, "Hf": 72, "Ta": 73, "W": 74, "Re": 75, "Os": 76,"Ir": 77, "Pt": 78, "Au": 79, "Hg": 80, "Tl": 81, "Pb": 82,
"Bi": 83, "Po": 84, "At": 85, "Rn": 86, "Fr": 87, "Ra": 88, "Ac": 89, "Th": 90, "Pa": 91, "U": 92, "Np": 93, "Pu": 94,
"Am": 95, "Cm": 96, "Bk": 97, "Cf": 98, "Es": 99, "Fm": 100, "Md": 101, "No": 102, "Lr": 103, "Rf": 104, "Db": 105,
"Sg": 106, "Bh": 107, "Hs": 108, "Mt": 109, "Ds": 110, "Rg": 111, "Cn": 112, "Nh": 113, "Fl": 114, "Mc": 115, "Lv": 116,
"Ts": 117, "Og": 118}
@classmethod
def e_orbit(self, element):
self.element = element
Atomic_Number = {"H": 1, "He": 2, "Li": 3, "Be": 4, "B": 5, "C": 6, "N": 7, "O": 8, "F": 9, "Ne": 10,
"Na": 11, "Mg": 12, "Al": 13, "Si": 14, "P": 15, "S": 16, "Cl": 17, "Ar": 18, "K": 19, "Ca": 20,"Sc": 21, "Ti": 22,
"V": 23, "Cr": 24, "Mn": 25, "Fe": 26, "Co": 27, "Ni": 28, "Cu": 29, "Zn": 30, "Ga": 31, "Ge": 32, "As": 33, "Se": 34,
"Br": 35, "Kr": 36, "Rb": 37, "Sr": 38,"Y": 39, "Zr": 40, "Nb": 41, "Mo": 42, "Tc": 43, "Ru": 44, "Rh": 45, "Pd": 46,
"Ag": 47,"Cd": 48, "In": 49, "Sn": 50, "Sb": 51, "Te": 52, "I": 53, "Xe": 54, "Cs": 55, "Ba": 56, "La": 57, "Ce": 58,
"Pr": 59,"Nd": 60, "Pm": 61, "Sm": 62, "Eu": 63, "Gd": 64, "Tb": 65, "Dy": 66, "Ho": 67, "Er": 68, "Tm": 69, "Yb": 70,
"Lu": 71, "Hf": 72, "Ta": 73, "W": 74, "Re": 75, "Os": 76,"Ir": 77, "Pt": 78, "Au": 79, "Hg": 80, "Tl": 81, "Pb": 82,
"Bi": 83, "Po": 84, "At": 85, "Rn": 86, "Fr": 87, "Ra": 88, "Ac": 89, "Th": 90, "Pa": 91, "U": 92, "Np": 93, "Pu": 94,
"Am": 95, "Cm": 96, "Bk": 97, "Cf": 98, "Es": 99, "Fm": 100, "Md": 101, "No": 102, "Lr": 103, "Rf": 104, "Db": 105,
"Sg": 106, "Bh": 107, "Hs": 108, "Mt": 109, "Ds": 110, "Rg": 111, "Cn": 112, "Nh": 113, "Fl": 114, "Mc": 115, "Lv": 116,
"Ts": 117, "Og": 118}
# the problem
e_dist = []
Atomic_number_tmp = Atomic_Number[element]
while Atomic_number_tmp != 0:
if Atomic_number_tmp == 1:
e_dist.append(1)
break
else:
e_dist.append(2)
Atomic_number_tmp - 2
if Atomic_number_tmp <= 0:
break
else:
if (Atomic_number_tmp - 8) == 0:
e_dist.append(8)
break
elif (Atomic_number_tmp - 8) > 0:
e_dist.append(8)
Atomic_number_tmp - 8
if Atomic_number_tmp <= 0:
break
elif Atomic_number_tmp > 0 and Atomic_number_tmp <= 7:
e_dist.append(Atomic_number_tmp)
elif (Atomic_number_tmp - 8) < 0:
break
break
print(e_dist)
# TEST FUNCTION
Atoms.e_orbit("Na")
The it's return [2, 8], But it must return [2, 8, 1]
I tried to read the code to understand the exact problem, but it is very complicated, I hope anybody can help my to solve this problem and make my code more readable.
Thank you for reading.
A:
The following code is my int4erpretation of your code.
global statements should be avoided at all cost.
You can make your attributs class atributes by adding them drictly to the class. It fullfills the same purpuse but it is much clearer and your functions loose code and are easyier to read. Thats just style thouhg. I NEVER use global.
You do not asing your changes. variable -1does not change the variable try variable -= 1.
You assinged your one twice. I assume by mistake.
I reduced the code just to get a bit of overview.
Statichmethod something similar as classmethod. But i am unsure about that. Please note that in your code the classmethod decorator is not at the right place. One whitespace is missing.
class Atoms:
ATOMIC_NUMBER = {"H": 1, "He": 2, "Li": 3, "Be": 4, "B": 5, "C": 6, "N": 7, "O": 8, "F": 9, "Ne": 10,
"Na": 11, "Mg": 12, "Al": 13, "Si": 14, "P": 15, "S": 16, "Cl": 17, "Ar": 18, "K": 19, "Ca": 20,"Sc": 21, "Ti": 22,
"V": 23, "Cr": 24, "Mn": 25, "Fe": 26, "Co": 27, "Ni": 28, "Cu": 29, "Zn": 30, "Ga": 31, "Ge": 32, "As": 33, "Se": 34,
"Br": 35, "Kr": 36, "Rb": 37, "Sr": 38,"Y": 39, "Zr": 40, "Nb": 41, "Mo": 42, "Tc": 43, "Ru": 44, "Rh": 45, "Pd": 46,
"Ag": 47,"Cd": 48, "In": 49, "Sn": 50, "Sb": 51, "Te": 52, "I": 53, "Xe": 54, "Cs": 55, "Ba": 56, "La": 57, "Ce": 58,
"Pr": 59,"Nd": 60, "Pm": 61, "Sm": 62, "Eu": 63, "Gd": 64, "Tb": 65, "Dy": 66, "Ho": 67, "Er": 68, "Tm": 69, "Yb": 70,
"Lu": 71, "Hf": 72, "Ta": 73, "W": 74, "Re": 75, "Os": 76,"Ir": 77, "Pt": 78, "Au": 79, "Hg": 80, "Tl": 81, "Pb": 82,
"Bi": 83, "Po": 84, "At": 85, "Rn": 86, "Fr": 87, "Ra": 88, "Ac": 89, "Th": 90, "Pa": 91, "U": 92, "Np": 93, "Pu": 94,
"Am": 95, "Cm": 96, "Bk": 97, "Cf": 98, "Es": 99, "Fm": 100, "Md": 101, "No": 102, "Lr": 103, "Rf": 104, "Db": 105,
"Sg": 106, "Bh": 107, "Hs": 108, "Mt": 109, "Ds": 110, "Rg": 111, "Cn": 112, "Nh": 113, "Fl": 114, "Mc": 115, "Lv": 116,
"Ts": 117, "Og": 118}
ATOM_INFO = {"H": ("Hydrogen", "Atomic Number : 1"), "He": ("Helium", "Atomic Number : 2"), "Li": ("Lithium", "Atomic Number : 3"),"Be": ("Beryllium", "Atomic Number : 4"),
"B": ("Boron", "Atomic Number : 5"),"C": ("Carbon", "Atomic Number : 6"), "N": ("Nitrogen", "Atomic Number : 7"),"O": ("Oxygen", "Atomic Number : 8"),
"F": ("Fluorine", "Atomic Number : 9"), "Ne": ("Neon", "Atomic Number : 10"), "Na": ("Sodium", "Atomic Number : 11"), "Mg": ("Magnesium", "Atomic Number : 12"),
"Al": ("Aluminium", "Atomic Number : 13"), "Si": ("Silicon", "Atomic Number : 14"), "P": ("Phosphorus", "Atomic Number : 15"), "S": ("Sulfur", "Atomic Number : 16"),
"Cl": ("Chlorine", "Atomic Number : 17"), "Ar": ("Argon", "Atomic Number : 18"), "K": ("Potassium", "Atomic Number : 19"), "Ca": ("Calcium", "Atomic Number : 20"),
"Sc": ("Scandium", "Atomic Number : 21"), "Ti": ("Titanium", "Atomic Number : 22"), "V": ("Vanadium", "Atomic Number : 23"), "Cr": ("Chromium", "Atomic Number : 24"),
"Mn": ("Manganese", "Atomic Number : 25"), "Fe": ("Iron", "Atomic Number : 26"), "Co": ("Cobalt", "Atomic Number : 27"), "Ni": ("Nickel", "Atomic Number : 28"),
"Cu": ("Copper", "Atomic Number : 29"), "Zn": ("Zinc", "Atomic Number : 30"), "Ga": ("Gallium", "Atomic Number : 31"), "Ge": ("Germanium", "Atomic Number : 32"),
"As": ("Arsenic", "Atomic Number : 33"), "Se": ("Selenium", "Atomic Number : 34"), "Br": ("Bromine", "Atomic Number : 35"), "Kr": ("Krypton", "Atomic Number : 36"),
"Rb": ("Rubidium", "Atomic Number : 37"), "Sr": ("Strontium", "Atomic Number : 38"), "Y": ("Yttrium", "Atomic Number : 39"), "Zr": ("Zirconium", "Atomic Number : 40"),
"Nb": ("Niobium", "Atomic Number : 41"), "Mo": ("Molybdenum", "Atomic Number : 42"), "Tc": ("Technetium", "Atomic Number : 43"), "Ru": ("Ruthenium", "Atomic Number : 44"),
"Rh": ("Rhodium", "Atomic Number : 45"), "Pd": ("Palladium", "Atomic Number : 46"), "Ag": ("Silver", "Atomic Number : 47"), "Cd": ("Cadmium", "Atomic Number : 48"),
"In": ("Indium", "Atomic Number : 49"), "Sn": ("Tin", "Atomic Number : 50"), "Sb": ("Antimony", "Atomic Number : 51"), "Te": ("Tellurium", "Atomic Number : 52"),
"I": ("Iodine", "Atomic Number : 53"), "Xe": ("Xenon", "Atomic Number : 54"), "Cs": ("Caesium", "Atomic Number : 55"), "Ba": ("Barium", "Atomic Number : 56"),
"La": ("Lanthanum", "Atomic Number : 57"), "Ce": ("Cerium", "Atomic Number : 58"), "Pr": ("Praseodymium", "Atomic Number : 59"), "Nd": ("Neodymium", "Atomic Number : 60"),
"Pm": ("Promethium", "Atomic Number : 61"), "Sm": ("Samarium", "Atomic Number : 62"), "Eu": ("Europium", "Atomic Number : 63"), "Gd": ("Gadolinium", "Atomic Number : 64"),
"Tb": ("Terbium", "Atomic Number : 65"), "Dy": ("Dysprosium", "Atomic Number : 66"), "Ho": ("Holmium", "Atomic Number : 67"), "Er": ("Erbium", "Atomic Number : 68"),
"Tm": ("Thulium", "Atomic Number : 69"), "Yb": ("Ytterbium", "Atomic Number : 70"), "Lu": ("Lutetium", "Atomic Number : 71"), "Hf": ("Hafnium", "Atomic Number : 72"),
"Ta": ("Tantalum", "Atomic Number : 73"), "W": ("Tungsten", "Atomic Number : 74"), "Re": ("Rhenium", "Atomic Number : 75"), "Os": ("Osmium", "Atomic Number : 76"),
"Ir": ("Iridium", "Atomic Number : 77"), "Pt": ("Platinum", "Atomic Number : 78"), "Au": ("Gold", "Atomic Number : 79"), "Hg": ("Mercury", "Atomic Number : 80"),
"Tl": ("Thallium", "Atomic Number : 81"), "Pb": ("Lead", "Atomic Number : 82"), "Bi": ("Bismuth", "Atomic Number : 83"), "Po": ("Polonium", "Atomic Number : 84"),
"At": ("Astatine", "Atomic Number : 85"), "Rn": ("Radon", "Atomic Number : 86"), "Fr": ("Francium", "Atomic Number : 87"), "Ra": ("Radium", "Atomic Number : 88"),
"Ac": ("Actinium", "Atomic Number : 89"), "Th": ("Thorium", "Atomic Number : 90"), "Pa": ("Protactinium", "Atomic Number : 91"), "U": ("Uranium", "Atomic Number : 92"),
"Np": ("Neptunium", "Atomic Number : 93"), "Pu": ("Plutonium", "Atomic Number : 94"), "Am": ("Americium", "Atomic Number : 95"), "Cm": ("Curium", "Atomic Number : 96"),
"Bk": ("Berkelium", "Atomic Number : 97"), "Cf": ("Californium", "Atomic Number : 98"), "Es": ("Einsteinium", "Atomic Number : 99"), "Fm": ("Fermium", "Atomic Number : 100"),
"Md": ("Mendelevium", "Atomic Number : bitcoin101"), "No": ("Nobelium", "Atomic Number : 102"), "Lr": ("Lawrencium", "Atomic Number : 103"), "Rf": ("Rutherfordium", "Atomic Number : 104"),
"Db": ("Dubnium", "Atomic Number : 105"), "Sg": ("Seaborgium", "Atomic Number : 106"), "Bh": ("Bohrium", "Atomic Number : 107"), "Hs": ("Hassium", "Atomic Number : 108"),
"Mt": ("Meitnerium", "Atomic Number : 109"), "Ds": ("Darmstadtium", "Atomic Number : 110"), "Rg": ("Roentgenium", "Atomic Number : 111"), "Cn": ("Copernicium", "Atomic Number : 112"),
"Nh": ("Nihonium", "Atomic Number : 113"), "Fl": ("Flerovium", "Atomic Number : 114"), "Mc": ("Moscovium", "Atomic Number : 115"), "Lv": ("Livermorium", "Atomic Number : 116"),
"Ts": ("Tennessine", "Atomic Number : 117"), "Og": ("Oganesson", "Atomic Number : 118")}
def __init__(self, protons, neutrons, electrons):
self.protons = protons
self.neutrons = neutrons
self.electrons = electrons
def atoms_info(the_atom_name):
if the_atom_name == 'all_info':
for key, value in Atoms.ATOM_INFO.items():
print(key, value)
elif the_atom_name == 'symbol':
temp = 1
for key in Atoms.ATOM_INFO:
print(f'Key_{temp} : {key}')
temp += 1
else:
print(Atoms.ATOM_INFO.get(the_atom_name, 'No atom has this symbol'))
@staticmethod
def e_orbit(element):
element = element
# the problem
e_dist = []
Atomic_number_tmp = Atoms.ATOMIC_NUMBER[element]
while Atomic_number_tmp > 0:
if Atomic_number_tmp == 1:
Atomic_number_tmp -= 1
e_dist.append(1)
break
else:
e_dist.append(2)
Atomic_number_tmp -= 2
if Atomic_number_tmp > 0:
if (Atomic_number_tmp - 8) == 0:
e_dist.append(8)
elif (Atomic_number_tmp - 8) > 0:
e_dist.append(8)
Atomic_number_tmp -= 8
if Atomic_number_tmp > 1 and Atomic_number_tmp <= 8:
# second append for one was here i am nit clear if that was correct
e_dist.append(Atomic_number_tmp)
elif (Atomic_number_tmp - 8) < 0:
continue
# TEST FUNCTION
Atoms.e_orbit("Na")
|
why my function don't return the last value?
|
I have written class called Atoms and I put inside it, in short, all the information you need in order to work on distributing the electrons of some atoms, and I put it in a dictionary dict, its symbol is the key and its atomic number is the value, and I made a set of conditional sentences in order to distribute the atoms and put them inside a list, but it excludes the last value and Don't put it on the list.
This is my code:
class Atoms:
def __init__(self, protons, neutrons, electrons):
self.protons = protons
self.neutrons = neutrons
self.electrons = electrons
def atoms_info(the_atom_name):
global Atoms_info
global Atomic_Number
Atoms_info = {"H": ("Hydrogen", "Atomic Number : 1"), "He": ("Helium", "Atomic Number : 2"), "Li": ("Lithium", "Atomic Number : 3"),"Be": ("Beryllium", "Atomic Number : 4"),
"B": ("Boron", "Atomic Number : 5"),"C": ("Carbon", "Atomic Number : 6"), "N": ("Nitrogen", "Atomic Number : 7"),"O": ("Oxygen", "Atomic Number : 8"),
"F": ("Fluorine", "Atomic Number : 9"), "Ne": ("Neon", "Atomic Number : 10"), "Na": ("Sodium", "Atomic Number : 11"), "Mg": ("Magnesium", "Atomic Number : 12"),
"Al": ("Aluminium", "Atomic Number : 13"), "Si": ("Silicon", "Atomic Number : 14"), "P": ("Phosphorus", "Atomic Number : 15"), "S": ("Sulfur", "Atomic Number : 16"),
"Cl": ("Chlorine", "Atomic Number : 17"), "Ar": ("Argon", "Atomic Number : 18"), "K": ("Potassium", "Atomic Number : 19"), "Ca": ("Calcium", "Atomic Number : 20"),
"Sc": ("Scandium", "Atomic Number : 21"), "Ti": ("Titanium", "Atomic Number : 22"), "V": ("Vanadium", "Atomic Number : 23"), "Cr": ("Chromium", "Atomic Number : 24"),
"Mn": ("Manganese", "Atomic Number : 25"), "Fe": ("Iron", "Atomic Number : 26"), "Co": ("Cobalt", "Atomic Number : 27"), "Ni": ("Nickel", "Atomic Number : 28"),
"Cu": ("Copper", "Atomic Number : 29"), "Zn": ("Zinc", "Atomic Number : 30"), "Ga": ("Gallium", "Atomic Number : 31"), "Ge": ("Germanium", "Atomic Number : 32"),
"As": ("Arsenic", "Atomic Number : 33"), "Se": ("Selenium", "Atomic Number : 34"), "Br": ("Bromine", "Atomic Number : 35"), "Kr": ("Krypton", "Atomic Number : 36"),
"Rb": ("Rubidium", "Atomic Number : 37"), "Sr": ("Strontium", "Atomic Number : 38"), "Y": ("Yttrium", "Atomic Number : 39"), "Zr": ("Zirconium", "Atomic Number : 40"),
"Nb": ("Niobium", "Atomic Number : 41"), "Mo": ("Molybdenum", "Atomic Number : 42"), "Tc": ("Technetium", "Atomic Number : 43"), "Ru": ("Ruthenium", "Atomic Number : 44"),
"Rh": ("Rhodium", "Atomic Number : 45"), "Pd": ("Palladium", "Atomic Number : 46"), "Ag": ("Silver", "Atomic Number : 47"), "Cd": ("Cadmium", "Atomic Number : 48"),
"In": ("Indium", "Atomic Number : 49"), "Sn": ("Tin", "Atomic Number : 50"), "Sb": ("Antimony", "Atomic Number : 51"), "Te": ("Tellurium", "Atomic Number : 52"),
"I": ("Iodine", "Atomic Number : 53"), "Xe": ("Xenon", "Atomic Number : 54"), "Cs": ("Caesium", "Atomic Number : 55"), "Ba": ("Barium", "Atomic Number : 56"),
"La": ("Lanthanum", "Atomic Number : 57"), "Ce": ("Cerium", "Atomic Number : 58"), "Pr": ("Praseodymium", "Atomic Number : 59"), "Nd": ("Neodymium", "Atomic Number : 60"),
"Pm": ("Promethium", "Atomic Number : 61"), "Sm": ("Samarium", "Atomic Number : 62"), "Eu": ("Europium", "Atomic Number : 63"), "Gd": ("Gadolinium", "Atomic Number : 64"),
"Tb": ("Terbium", "Atomic Number : 65"), "Dy": ("Dysprosium", "Atomic Number : 66"), "Ho": ("Holmium", "Atomic Number : 67"), "Er": ("Erbium", "Atomic Number : 68"),
"Tm": ("Thulium", "Atomic Number : 69"), "Yb": ("Ytterbium", "Atomic Number : 70"), "Lu": ("Lutetium", "Atomic Number : 71"), "Hf": ("Hafnium", "Atomic Number : 72"),
"Ta": ("Tantalum", "Atomic Number : 73"), "W": ("Tungsten", "Atomic Number : 74"), "Re": ("Rhenium", "Atomic Number : 75"), "Os": ("Osmium", "Atomic Number : 76"),
"Ir": ("Iridium", "Atomic Number : 77"), "Pt": ("Platinum", "Atomic Number : 78"), "Au": ("Gold", "Atomic Number : 79"), "Hg": ("Mercury", "Atomic Number : 80"),
"Tl": ("Thallium", "Atomic Number : 81"), "Pb": ("Lead", "Atomic Number : 82"), "Bi": ("Bismuth", "Atomic Number : 83"), "Po": ("Polonium", "Atomic Number : 84"),
"At": ("Astatine", "Atomic Number : 85"), "Rn": ("Radon", "Atomic Number : 86"), "Fr": ("Francium", "Atomic Number : 87"), "Ra": ("Radium", "Atomic Number : 88"),
"Ac": ("Actinium", "Atomic Number : 89"), "Th": ("Thorium", "Atomic Number : 90"), "Pa": ("Protactinium", "Atomic Number : 91"), "U": ("Uranium", "Atomic Number : 92"),
"Np": ("Neptunium", "Atomic Number : 93"), "Pu": ("Plutonium", "Atomic Number : 94"), "Am": ("Americium", "Atomic Number : 95"), "Cm": ("Curium", "Atomic Number : 96"),
"Bk": ("Berkelium", "Atomic Number : 97"), "Cf": ("Californium", "Atomic Number : 98"), "Es": ("Einsteinium", "Atomic Number : 99"), "Fm": ("Fermium", "Atomic Number : 100"),
"Md": ("Mendelevium", "Atomic Number : bitcoin101"), "No": ("Nobelium", "Atomic Number : 102"), "Lr": ("Lawrencium", "Atomic Number : 103"), "Rf": ("Rutherfordium", "Atomic Number : 104"),
"Db": ("Dubnium", "Atomic Number : 105"), "Sg": ("Seaborgium", "Atomic Number : 106"), "Bh": ("Bohrium", "Atomic Number : 107"), "Hs": ("Hassium", "Atomic Number : 108"),
"Mt": ("Meitnerium", "Atomic Number : 109"), "Ds": ("Darmstadtium", "Atomic Number : 110"), "Rg": ("Roentgenium", "Atomic Number : 111"), "Cn": ("Copernicium", "Atomic Number : 112"),
"Nh": ("Nihonium", "Atomic Number : 113"), "Fl": ("Flerovium", "Atomic Number : 114"), "Mc": ("Moscovium", "Atomic Number : 115"), "Lv": ("Livermorium", "Atomic Number : 116"),
"Ts": ("Tennessine", "Atomic Number : 117"), "Og": ("Oganesson", "Atomic Number : 118")}
if the_atom_name == 'all_info':
for key, value in Atoms_info.items():
print(key, value)
elif the_atom_name == 'symbol':
temp = 1
for key in Atoms_info:
print(f'Key_{temp} : {key}')
temp += 1
else:
print(Atoms_info.get(the_atom_name, 'No atom has this symbol'))
Atomic_Number = {"H": 1, "He": 2, "Li": 3, "Be": 4, "B": 5, "C": 6, "N": 7, "O": 8, "F": 9, "Ne": 10,
"Na": 11, "Mg": 12, "Al": 13, "Si": 14, "P": 15, "S": 16, "Cl": 17, "Ar": 18, "K": 19, "Ca": 20,"Sc": 21, "Ti": 22,
"V": 23, "Cr": 24, "Mn": 25, "Fe": 26, "Co": 27, "Ni": 28, "Cu": 29, "Zn": 30, "Ga": 31, "Ge": 32, "As": 33, "Se": 34,
"Br": 35, "Kr": 36, "Rb": 37, "Sr": 38,"Y": 39, "Zr": 40, "Nb": 41, "Mo": 42, "Tc": 43, "Ru": 44, "Rh": 45, "Pd": 46,
"Ag": 47,"Cd": 48, "In": 49, "Sn": 50, "Sb": 51, "Te": 52, "I": 53, "Xe": 54, "Cs": 55, "Ba": 56, "La": 57, "Ce": 58,
"Pr": 59,"Nd": 60, "Pm": 61, "Sm": 62, "Eu": 63, "Gd": 64, "Tb": 65, "Dy": 66, "Ho": 67, "Er": 68, "Tm": 69, "Yb": 70,
"Lu": 71, "Hf": 72, "Ta": 73, "W": 74, "Re": 75, "Os": 76,"Ir": 77, "Pt": 78, "Au": 79, "Hg": 80, "Tl": 81, "Pb": 82,
"Bi": 83, "Po": 84, "At": 85, "Rn": 86, "Fr": 87, "Ra": 88, "Ac": 89, "Th": 90, "Pa": 91, "U": 92, "Np": 93, "Pu": 94,
"Am": 95, "Cm": 96, "Bk": 97, "Cf": 98, "Es": 99, "Fm": 100, "Md": 101, "No": 102, "Lr": 103, "Rf": 104, "Db": 105,
"Sg": 106, "Bh": 107, "Hs": 108, "Mt": 109, "Ds": 110, "Rg": 111, "Cn": 112, "Nh": 113, "Fl": 114, "Mc": 115, "Lv": 116,
"Ts": 117, "Og": 118}
@classmethod
def e_orbit(self, element):
self.element = element
Atomic_Number = {"H": 1, "He": 2, "Li": 3, "Be": 4, "B": 5, "C": 6, "N": 7, "O": 8, "F": 9, "Ne": 10,
"Na": 11, "Mg": 12, "Al": 13, "Si": 14, "P": 15, "S": 16, "Cl": 17, "Ar": 18, "K": 19, "Ca": 20,"Sc": 21, "Ti": 22,
"V": 23, "Cr": 24, "Mn": 25, "Fe": 26, "Co": 27, "Ni": 28, "Cu": 29, "Zn": 30, "Ga": 31, "Ge": 32, "As": 33, "Se": 34,
"Br": 35, "Kr": 36, "Rb": 37, "Sr": 38,"Y": 39, "Zr": 40, "Nb": 41, "Mo": 42, "Tc": 43, "Ru": 44, "Rh": 45, "Pd": 46,
"Ag": 47,"Cd": 48, "In": 49, "Sn": 50, "Sb": 51, "Te": 52, "I": 53, "Xe": 54, "Cs": 55, "Ba": 56, "La": 57, "Ce": 58,
"Pr": 59,"Nd": 60, "Pm": 61, "Sm": 62, "Eu": 63, "Gd": 64, "Tb": 65, "Dy": 66, "Ho": 67, "Er": 68, "Tm": 69, "Yb": 70,
"Lu": 71, "Hf": 72, "Ta": 73, "W": 74, "Re": 75, "Os": 76,"Ir": 77, "Pt": 78, "Au": 79, "Hg": 80, "Tl": 81, "Pb": 82,
"Bi": 83, "Po": 84, "At": 85, "Rn": 86, "Fr": 87, "Ra": 88, "Ac": 89, "Th": 90, "Pa": 91, "U": 92, "Np": 93, "Pu": 94,
"Am": 95, "Cm": 96, "Bk": 97, "Cf": 98, "Es": 99, "Fm": 100, "Md": 101, "No": 102, "Lr": 103, "Rf": 104, "Db": 105,
"Sg": 106, "Bh": 107, "Hs": 108, "Mt": 109, "Ds": 110, "Rg": 111, "Cn": 112, "Nh": 113, "Fl": 114, "Mc": 115, "Lv": 116,
"Ts": 117, "Og": 118}
# the problem
e_dist = []
Atomic_number_tmp = Atomic_Number[element]
while Atomic_number_tmp != 0:
if Atomic_number_tmp == 1:
e_dist.append(1)
break
else:
e_dist.append(2)
Atomic_number_tmp - 2
if Atomic_number_tmp <= 0:
break
else:
if (Atomic_number_tmp - 8) == 0:
e_dist.append(8)
break
elif (Atomic_number_tmp - 8) > 0:
e_dist.append(8)
Atomic_number_tmp - 8
if Atomic_number_tmp <= 0:
break
elif Atomic_number_tmp > 0 and Atomic_number_tmp <= 7:
e_dist.append(Atomic_number_tmp)
elif (Atomic_number_tmp - 8) < 0:
break
break
print(e_dist)
# TEST FUNCTION
Atoms.e_orbit("Na")
The it's return [2, 8], But it must return [2, 8, 1]
I tried to read the code to understand the exact problem, but it is very complicated, I hope anybody can help my to solve this problem and make my code more readable.
Thank you for reading.
|
[
"The following code is my int4erpretation of your code.\n\nglobal statements should be avoided at all cost.\nYou can make your attributs class atributes by adding them drictly to the class. It fullfills the same purpuse but it is much clearer and your functions loose code and are easyier to read. Thats just style thouhg. I NEVER use global.\nYou do not asing your changes. variable -1does not change the variable try variable -= 1.\nYou assinged your one twice. I assume by mistake.\nI reduced the code just to get a bit of overview.\nStatichmethod something similar as classmethod. But i am unsure about that. Please note that in your code the classmethod decorator is not at the right place. One whitespace is missing.\n\nclass Atoms:\n ATOMIC_NUMBER = {\"H\": 1, \"He\": 2, \"Li\": 3, \"Be\": 4, \"B\": 5, \"C\": 6, \"N\": 7, \"O\": 8, \"F\": 9, \"Ne\": 10,\n \"Na\": 11, \"Mg\": 12, \"Al\": 13, \"Si\": 14, \"P\": 15, \"S\": 16, \"Cl\": 17, \"Ar\": 18, \"K\": 19, \"Ca\": 20,\"Sc\": 21, \"Ti\": 22,\n \"V\": 23, \"Cr\": 24, \"Mn\": 25, \"Fe\": 26, \"Co\": 27, \"Ni\": 28, \"Cu\": 29, \"Zn\": 30, \"Ga\": 31, \"Ge\": 32, \"As\": 33, \"Se\": 34,\n \"Br\": 35, \"Kr\": 36, \"Rb\": 37, \"Sr\": 38,\"Y\": 39, \"Zr\": 40, \"Nb\": 41, \"Mo\": 42, \"Tc\": 43, \"Ru\": 44, \"Rh\": 45, \"Pd\": 46,\n \"Ag\": 47,\"Cd\": 48, \"In\": 49, \"Sn\": 50, \"Sb\": 51, \"Te\": 52, \"I\": 53, \"Xe\": 54, \"Cs\": 55, \"Ba\": 56, \"La\": 57, \"Ce\": 58,\n \"Pr\": 59,\"Nd\": 60, \"Pm\": 61, \"Sm\": 62, \"Eu\": 63, \"Gd\": 64, \"Tb\": 65, \"Dy\": 66, \"Ho\": 67, \"Er\": 68, \"Tm\": 69, \"Yb\": 70,\n \"Lu\": 71, \"Hf\": 72, \"Ta\": 73, \"W\": 74, \"Re\": 75, \"Os\": 76,\"Ir\": 77, \"Pt\": 78, \"Au\": 79, \"Hg\": 80, \"Tl\": 81, \"Pb\": 82,\n \"Bi\": 83, \"Po\": 84, \"At\": 85, \"Rn\": 86, \"Fr\": 87, \"Ra\": 88, \"Ac\": 89, \"Th\": 90, \"Pa\": 91, \"U\": 92, \"Np\": 93, \"Pu\": 94,\n \"Am\": 95, \"Cm\": 96, \"Bk\": 97, \"Cf\": 98, \"Es\": 99, \"Fm\": 100, \"Md\": 101, \"No\": 102, \"Lr\": 103, \"Rf\": 104, \"Db\": 105,\n \"Sg\": 106, \"Bh\": 107, \"Hs\": 108, \"Mt\": 109, \"Ds\": 110, \"Rg\": 111, \"Cn\": 112, \"Nh\": 113, \"Fl\": 114, \"Mc\": 115, \"Lv\": 116,\n \"Ts\": 117, \"Og\": 118}\n \n ATOM_INFO = {\"H\": (\"Hydrogen\", \"Atomic Number : 1\"), \"He\": (\"Helium\", \"Atomic Number : 2\"), \"Li\": (\"Lithium\", \"Atomic Number : 3\"),\"Be\": (\"Beryllium\", \"Atomic Number : 4\"),\n \"B\": (\"Boron\", \"Atomic Number : 5\"),\"C\": (\"Carbon\", \"Atomic Number : 6\"), \"N\": (\"Nitrogen\", \"Atomic Number : 7\"),\"O\": (\"Oxygen\", \"Atomic Number : 8\"),\n \"F\": (\"Fluorine\", \"Atomic Number : 9\"), \"Ne\": (\"Neon\", \"Atomic Number : 10\"), \"Na\": (\"Sodium\", \"Atomic Number : 11\"), \"Mg\": (\"Magnesium\", \"Atomic Number : 12\"),\n \"Al\": (\"Aluminium\", \"Atomic Number : 13\"), \"Si\": (\"Silicon\", \"Atomic Number : 14\"), \"P\": (\"Phosphorus\", \"Atomic Number : 15\"), \"S\": (\"Sulfur\", \"Atomic Number : 16\"),\n \"Cl\": (\"Chlorine\", \"Atomic Number : 17\"), \"Ar\": (\"Argon\", \"Atomic Number : 18\"), \"K\": (\"Potassium\", \"Atomic Number : 19\"), \"Ca\": (\"Calcium\", \"Atomic Number : 20\"),\n \"Sc\": (\"Scandium\", \"Atomic Number : 21\"), \"Ti\": (\"Titanium\", \"Atomic Number : 22\"), \"V\": (\"Vanadium\", \"Atomic Number : 23\"), \"Cr\": (\"Chromium\", \"Atomic Number : 24\"),\n \"Mn\": (\"Manganese\", \"Atomic Number : 25\"), \"Fe\": (\"Iron\", \"Atomic Number : 26\"), \"Co\": (\"Cobalt\", \"Atomic Number : 27\"), \"Ni\": (\"Nickel\", \"Atomic Number : 28\"),\n \"Cu\": (\"Copper\", \"Atomic Number : 29\"), \"Zn\": (\"Zinc\", \"Atomic Number : 30\"), \"Ga\": (\"Gallium\", \"Atomic Number : 31\"), \"Ge\": (\"Germanium\", \"Atomic Number : 32\"),\n \"As\": (\"Arsenic\", \"Atomic Number : 33\"), \"Se\": (\"Selenium\", \"Atomic Number : 34\"), \"Br\": (\"Bromine\", \"Atomic Number : 35\"), \"Kr\": (\"Krypton\", \"Atomic Number : 36\"),\n \"Rb\": (\"Rubidium\", \"Atomic Number : 37\"), \"Sr\": (\"Strontium\", \"Atomic Number : 38\"), \"Y\": (\"Yttrium\", \"Atomic Number : 39\"), \"Zr\": (\"Zirconium\", \"Atomic Number : 40\"),\n \"Nb\": (\"Niobium\", \"Atomic Number : 41\"), \"Mo\": (\"Molybdenum\", \"Atomic Number : 42\"), \"Tc\": (\"Technetium\", \"Atomic Number : 43\"), \"Ru\": (\"Ruthenium\", \"Atomic Number : 44\"),\n \"Rh\": (\"Rhodium\", \"Atomic Number : 45\"), \"Pd\": (\"Palladium\", \"Atomic Number : 46\"), \"Ag\": (\"Silver\", \"Atomic Number : 47\"), \"Cd\": (\"Cadmium\", \"Atomic Number : 48\"),\n \"In\": (\"Indium\", \"Atomic Number : 49\"), \"Sn\": (\"Tin\", \"Atomic Number : 50\"), \"Sb\": (\"Antimony\", \"Atomic Number : 51\"), \"Te\": (\"Tellurium\", \"Atomic Number : 52\"),\n \"I\": (\"Iodine\", \"Atomic Number : 53\"), \"Xe\": (\"Xenon\", \"Atomic Number : 54\"), \"Cs\": (\"Caesium\", \"Atomic Number : 55\"), \"Ba\": (\"Barium\", \"Atomic Number : 56\"),\n \"La\": (\"Lanthanum\", \"Atomic Number : 57\"), \"Ce\": (\"Cerium\", \"Atomic Number : 58\"), \"Pr\": (\"Praseodymium\", \"Atomic Number : 59\"), \"Nd\": (\"Neodymium\", \"Atomic Number : 60\"),\n \"Pm\": (\"Promethium\", \"Atomic Number : 61\"), \"Sm\": (\"Samarium\", \"Atomic Number : 62\"), \"Eu\": (\"Europium\", \"Atomic Number : 63\"), \"Gd\": (\"Gadolinium\", \"Atomic Number : 64\"),\n \"Tb\": (\"Terbium\", \"Atomic Number : 65\"), \"Dy\": (\"Dysprosium\", \"Atomic Number : 66\"), \"Ho\": (\"Holmium\", \"Atomic Number : 67\"), \"Er\": (\"Erbium\", \"Atomic Number : 68\"),\n \"Tm\": (\"Thulium\", \"Atomic Number : 69\"), \"Yb\": (\"Ytterbium\", \"Atomic Number : 70\"), \"Lu\": (\"Lutetium\", \"Atomic Number : 71\"), \"Hf\": (\"Hafnium\", \"Atomic Number : 72\"),\n \"Ta\": (\"Tantalum\", \"Atomic Number : 73\"), \"W\": (\"Tungsten\", \"Atomic Number : 74\"), \"Re\": (\"Rhenium\", \"Atomic Number : 75\"), \"Os\": (\"Osmium\", \"Atomic Number : 76\"),\n \"Ir\": (\"Iridium\", \"Atomic Number : 77\"), \"Pt\": (\"Platinum\", \"Atomic Number : 78\"), \"Au\": (\"Gold\", \"Atomic Number : 79\"), \"Hg\": (\"Mercury\", \"Atomic Number : 80\"),\n \"Tl\": (\"Thallium\", \"Atomic Number : 81\"), \"Pb\": (\"Lead\", \"Atomic Number : 82\"), \"Bi\": (\"Bismuth\", \"Atomic Number : 83\"), \"Po\": (\"Polonium\", \"Atomic Number : 84\"),\n \"At\": (\"Astatine\", \"Atomic Number : 85\"), \"Rn\": (\"Radon\", \"Atomic Number : 86\"), \"Fr\": (\"Francium\", \"Atomic Number : 87\"), \"Ra\": (\"Radium\", \"Atomic Number : 88\"),\n \"Ac\": (\"Actinium\", \"Atomic Number : 89\"), \"Th\": (\"Thorium\", \"Atomic Number : 90\"), \"Pa\": (\"Protactinium\", \"Atomic Number : 91\"), \"U\": (\"Uranium\", \"Atomic Number : 92\"),\n \"Np\": (\"Neptunium\", \"Atomic Number : 93\"), \"Pu\": (\"Plutonium\", \"Atomic Number : 94\"), \"Am\": (\"Americium\", \"Atomic Number : 95\"), \"Cm\": (\"Curium\", \"Atomic Number : 96\"),\n \"Bk\": (\"Berkelium\", \"Atomic Number : 97\"), \"Cf\": (\"Californium\", \"Atomic Number : 98\"), \"Es\": (\"Einsteinium\", \"Atomic Number : 99\"), \"Fm\": (\"Fermium\", \"Atomic Number : 100\"),\n \"Md\": (\"Mendelevium\", \"Atomic Number : bitcoin101\"), \"No\": (\"Nobelium\", \"Atomic Number : 102\"), \"Lr\": (\"Lawrencium\", \"Atomic Number : 103\"), \"Rf\": (\"Rutherfordium\", \"Atomic Number : 104\"),\n \"Db\": (\"Dubnium\", \"Atomic Number : 105\"), \"Sg\": (\"Seaborgium\", \"Atomic Number : 106\"), \"Bh\": (\"Bohrium\", \"Atomic Number : 107\"), \"Hs\": (\"Hassium\", \"Atomic Number : 108\"),\n \"Mt\": (\"Meitnerium\", \"Atomic Number : 109\"), \"Ds\": (\"Darmstadtium\", \"Atomic Number : 110\"), \"Rg\": (\"Roentgenium\", \"Atomic Number : 111\"), \"Cn\": (\"Copernicium\", \"Atomic Number : 112\"),\n \"Nh\": (\"Nihonium\", \"Atomic Number : 113\"), \"Fl\": (\"Flerovium\", \"Atomic Number : 114\"), \"Mc\": (\"Moscovium\", \"Atomic Number : 115\"), \"Lv\": (\"Livermorium\", \"Atomic Number : 116\"),\n \"Ts\": (\"Tennessine\", \"Atomic Number : 117\"), \"Og\": (\"Oganesson\", \"Atomic Number : 118\")}\n \n def __init__(self, protons, neutrons, electrons):\n self.protons = protons\n self.neutrons = neutrons\n self.electrons = electrons\n\n def atoms_info(the_atom_name):\n \n if the_atom_name == 'all_info':\n for key, value in Atoms.ATOM_INFO.items():\n print(key, value)\n\n elif the_atom_name == 'symbol':\n temp = 1\n for key in Atoms.ATOM_INFO:\n print(f'Key_{temp} : {key}')\n temp += 1\n else:\n print(Atoms.ATOM_INFO.get(the_atom_name, 'No atom has this symbol'))\n \n @staticmethod\n def e_orbit(element):\n element = element\n \n \n # the problem\n e_dist = []\n Atomic_number_tmp = Atoms.ATOMIC_NUMBER[element]\n while Atomic_number_tmp > 0:\n\n if Atomic_number_tmp == 1:\n Atomic_number_tmp -= 1\n e_dist.append(1)\n break\n\n else:\n e_dist.append(2)\n Atomic_number_tmp -= 2\n \n if Atomic_number_tmp > 0:\n if (Atomic_number_tmp - 8) == 0:\n e_dist.append(8)\n\n elif (Atomic_number_tmp - 8) > 0:\n e_dist.append(8)\n Atomic_number_tmp -= 8\n\n if Atomic_number_tmp > 1 and Atomic_number_tmp <= 8:\n # second append for one was here i am nit clear if that was correct\n e_dist.append(Atomic_number_tmp)\n\n elif (Atomic_number_tmp - 8) < 0:\n continue\n\n# TEST FUNCTION\nAtoms.e_orbit(\"Na\")\n\n"
] |
[
0
] |
[] |
[] |
[
"class",
"if_statement",
"oop",
"python"
] |
stackoverflow_0074583005_class_if_statement_oop_python.txt
|
Q:
AttributeError: module 'cv2' has no attribute 'imread'
(i'm on mac os 10.8.5)
I'm using Python 3 (through jupyter notebook) and trying to import cv2
I did import cv2 succefully, but when I type im_g = cv2.imread("smallgray.png", 0) I get this error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-7-5eb2880672d2> in <module>()
----> 1 im_g = cv2.imread("smallgray.png", 0)
AttributeError: module 'cv2' has no attribute 'imread'
I also checked dir(cv2) and I get:
['__doc__', '__loader__', '__name__', '__package__', '__path__', '__spec__'
I guess a lot of functions are missing...
Is it due to a wrong opencv installation ?
Actually I struggled a lot to get opencv and I guess I installed it 'too many times' and different ways via Terminal. (brew, pip)
Should I uninstall opencv and start over ? How can I do this properly ?
Thx in advance
A:
It might be the case that you installed it in the wrong way. In my case as well, I installed OpenCV wrongly so I uninstalled it completely then reinstalled it which caused it to work.
Please notice the sequence of uninstalling and installing:
Uninstall:
pip uninstall opencv-python
pip uninstall opencv-contrib-python
Install:
pip install opencv-contrib-python
pip install opencv-python
A:
I was have this problem too, and i solved it, the problem was been in i named my script cv2.py, i'm just rename it to something else.
A:
Reader's problem could be, that a wrong library (cv2 package) has been installed.
I installed opencv-python3 instead of opencv-python for example.
So in case you have PyCharm IDE, go to File->Settings->Project: *->Python Interpreter and see what you have listed there:
Make sure, you have installed opencv-python.
If you have also other similar names, it should be fine - in my case it works.
A:
This might happen if you have named one of your files as 'cv2.py'. So when you 'import cv2', the system accesses your file instead of the actual library. So try renaming cv2.py' to any other name and your code should work fine.
A:
I had the same issue, this turned out to solve the problem:
from cv2 import cv2
im_g=cv2.imread("smallgray.png", 0)
print(im_g)
A:
Do cv2.cv2.imread()
This should work in most of the cases. Also, take a look here.
A:
Check:
brew list | grep opencv
If it doesn't installed then try:
brew install opencv
A:
it works with me:
pip install opencv-python
pip install opencv-contrib-python
source : https://pypi.org/project/opencv-python/
A:
I faced Similar issue,On Ubuntu
I had installed open-cv using the comand:
sudo pip3 install opencv-python3
I Uninstalled opencv, By:
sudo pip3 uninstall opencv-python3
Then reinstalled it Using the following Code:
pip3 install opencv-python
A:
I also faced this problem.
And get a solution by changing the current cv2.py to cv.py(You can name whatever you like except the name of packages in use).
Little Explanations
Saving the current working file as the name of cv2.py, when we try to run the file it imports the current file with import cv2 statement, not actual cv2 module. This whole thing is causing this whole Error.
A:
The main problem is that you have your file or folder named "cv2", it is not permitted in Python. The way to solve is change the name and then your code will be run
A:
The same issue has recently appeared within my code and had no idea of what's happening. Tried different methods such as uninstalling opencv-python.
Coming to the naming of the file that I am working with, I definitely had no problem that might cause a collapse with the name of the library.
I have deleted the opencv-python, cleaned all of the package-related caches, and then reinstalled the opencv-python and opencv-contrib-python. Now, it is working fine and I can say that no issues have appeared yet.
P.S I am using Arch Linux. If you wonder about how to clear caches, try looking at this source. I hope it helps. Keep learning and exploring, thanks!
A:
I personally had to uninstall all previous installations dealing with opencv :
pip uninstall opencv-python
pip uninstall opencv-contrib-python
pip uninstall opencv-contrib-python-headless
Then I deleted all files that had to do with opencv too in site-package
after the uninstallation, files related to opencv like opencv_contrib_python-4.6.0.66.dist-info remained and caused errors.
Once all these files were deleted I reinstalled opencv:
pip install opencv-python
now it works for me
A:
using cv2 on vscode
i was having this problem but nothing worked. Turns out that i named my file as "cv2.py" so it was importing itself
"Generally, the Python Circular Import problem occurs when you accidentally name your working file the same as the module name and those modules depend on each other. This way the python opens the same file which causes a circular loop and eventually throws an error."
|
AttributeError: module 'cv2' has no attribute 'imread'
|
(i'm on mac os 10.8.5)
I'm using Python 3 (through jupyter notebook) and trying to import cv2
I did import cv2 succefully, but when I type im_g = cv2.imread("smallgray.png", 0) I get this error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-7-5eb2880672d2> in <module>()
----> 1 im_g = cv2.imread("smallgray.png", 0)
AttributeError: module 'cv2' has no attribute 'imread'
I also checked dir(cv2) and I get:
['__doc__', '__loader__', '__name__', '__package__', '__path__', '__spec__'
I guess a lot of functions are missing...
Is it due to a wrong opencv installation ?
Actually I struggled a lot to get opencv and I guess I installed it 'too many times' and different ways via Terminal. (brew, pip)
Should I uninstall opencv and start over ? How can I do this properly ?
Thx in advance
|
[
"It might be the case that you installed it in the wrong way. In my case as well, I installed OpenCV wrongly so I uninstalled it completely then reinstalled it which caused it to work.\nPlease notice the sequence of uninstalling and installing:\nUninstall:\npip uninstall opencv-python\npip uninstall opencv-contrib-python\n\nInstall:\npip install opencv-contrib-python\npip install opencv-python\n\n",
"I was have this problem too, and i solved it, the problem was been in i named my script cv2.py, i'm just rename it to something else.\n",
"Reader's problem could be, that a wrong library (cv2 package) has been installed.\nI installed opencv-python3 instead of opencv-python for example.\nSo in case you have PyCharm IDE, go to File->Settings->Project: *->Python Interpreter and see what you have listed there:\n\nMake sure, you have installed opencv-python.\nIf you have also other similar names, it should be fine - in my case it works.\n",
"This might happen if you have named one of your files as 'cv2.py'. So when you 'import cv2', the system accesses your file instead of the actual library. So try renaming cv2.py' to any other name and your code should work fine.\n",
"I had the same issue, this turned out to solve the problem:\nfrom cv2 import cv2\nim_g=cv2.imread(\"smallgray.png\", 0)\nprint(im_g)\n\n",
"Do cv2.cv2.imread()\nThis should work in most of the cases. Also, take a look here.\n",
"Check:\nbrew list | grep opencv\n\nIf it doesn't installed then try:\nbrew install opencv\n\n",
"it works with me: \n\npip install opencv-python \npip install opencv-contrib-python\n\nsource : https://pypi.org/project/opencv-python/\n",
"I faced Similar issue,On Ubuntu\nI had installed open-cv using the comand:\nsudo pip3 install opencv-python3\n\nI Uninstalled opencv, By:\nsudo pip3 uninstall opencv-python3\n\nThen reinstalled it Using the following Code:\npip3 install opencv-python\n\n",
"I also faced this problem.\nAnd get a solution by changing the current cv2.py to cv.py(You can name whatever you like except the name of packages in use).\nLittle Explanations\n\nSaving the current working file as the name of cv2.py, when we try to run the file it imports the current file with import cv2 statement, not actual cv2 module. This whole thing is causing this whole Error.\n\n",
"The main problem is that you have your file or folder named \"cv2\", it is not permitted in Python. The way to solve is change the name and then your code will be run\n",
"The same issue has recently appeared within my code and had no idea of what's happening. Tried different methods such as uninstalling opencv-python.\nComing to the naming of the file that I am working with, I definitely had no problem that might cause a collapse with the name of the library.\nI have deleted the opencv-python, cleaned all of the package-related caches, and then reinstalled the opencv-python and opencv-contrib-python. Now, it is working fine and I can say that no issues have appeared yet.\nP.S I am using Arch Linux. If you wonder about how to clear caches, try looking at this source. I hope it helps. Keep learning and exploring, thanks!\n",
"I personally had to uninstall all previous installations dealing with opencv :\npip uninstall opencv-python\npip uninstall opencv-contrib-python\npip uninstall opencv-contrib-python-headless\n\nThen I deleted all files that had to do with opencv too in site-package\nafter the uninstallation, files related to opencv like opencv_contrib_python-4.6.0.66.dist-info remained and caused errors.\nOnce all these files were deleted I reinstalled opencv:\npip install opencv-python\n\nnow it works for me\n",
"using cv2 on vscode\ni was having this problem but nothing worked. Turns out that i named my file as \"cv2.py\" so it was importing itself\n\"Generally, the Python Circular Import problem occurs when you accidentally name your working file the same as the module name and those modules depend on each other. This way the python opens the same file which causes a circular loop and eventually throws an error.\"\n"
] |
[
9,
4,
2,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
"Perhaps you have just installed opencv-contrib-python and not opencv-python.\nTry this out, it worked for me-\n\nFirst uninstall:\n\npip uninstall opencv-python\npip uninstall opencv-contrib-python\n\n\nthen install:\n\npip install opencv-contrib-python==3.4.2.16\npip install opencv-python==3.4.2.16\n\nYou can refer here.\n"
] |
[
-1
] |
[
"opencv",
"python"
] |
stackoverflow_0047857141_opencv_python.txt
|
Q:
Populate Adjacent Value in Pandas Column When String is Duplicated
I'm attempting to overwrite the value named in a column called 'Group' when the value in a column called 'Keyword' is a duplicate with the adjacent value.
For example, because the string 'commercial office cleaning services' is duplicated, I'd like to overwrite the adjacent column to 'commercial cleaning services'.
Example Data
Desired Output
Minimum Reproducible Example
import pandas as pd
data = [
["commercial cleaning services", "commercial cleaning services"],
["commercial office cleaning services", "commercial cleaning services"],
["janitorial cleaning services", "commercial cleaning services"],
["commercial office services", "commercial cleaning"],
]
df = pd.DataFrame(data, columns=["Keyword", "Group"])
print(df)
I'm fairly new to pandas and not sure where to start, I've reached a dead end Googling and searching stackoverflow.
A:
IIUC, use duplicated with mask and ffill :
#is the keyword duplicated ?
m = df['Keyword'].duplicated()
df['Group'] = df['Group'].mask(m).ffill()
# Output:
print(df)
Keyword Group
0 commercial cleaning services commercial cleaning services
1 commercial office cleaning services commercial cleaning services
2 janitorial cleaning services commercial cleaning services
3 commercial office cleaning services commercial cleaning services
NB: The reproducible example does not match the image of the input (https://i.stack.imgur.com/fPWPa.png)
|
Populate Adjacent Value in Pandas Column When String is Duplicated
|
I'm attempting to overwrite the value named in a column called 'Group' when the value in a column called 'Keyword' is a duplicate with the adjacent value.
For example, because the string 'commercial office cleaning services' is duplicated, I'd like to overwrite the adjacent column to 'commercial cleaning services'.
Example Data
Desired Output
Minimum Reproducible Example
import pandas as pd
data = [
["commercial cleaning services", "commercial cleaning services"],
["commercial office cleaning services", "commercial cleaning services"],
["janitorial cleaning services", "commercial cleaning services"],
["commercial office services", "commercial cleaning"],
]
df = pd.DataFrame(data, columns=["Keyword", "Group"])
print(df)
I'm fairly new to pandas and not sure where to start, I've reached a dead end Googling and searching stackoverflow.
|
[
"IIUC, use duplicated with mask and ffill :\n#is the keyword duplicated ?\nm = df['Keyword'].duplicated()\n\ndf['Group'] = df['Group'].mask(m).ffill()\n\n# Output:\nprint(df)\n\n Keyword Group\n0 commercial cleaning services commercial cleaning services\n1 commercial office cleaning services commercial cleaning services\n2 janitorial cleaning services commercial cleaning services\n3 commercial office cleaning services commercial cleaning services\n\nNB: The reproducible example does not match the image of the input (https://i.stack.imgur.com/fPWPa.png)\n"
] |
[
2
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074583388_pandas_python.txt
|
Q:
Tensorflow Callback as Custom Metric for CTC
In an attempt to yield more metrics during the training of my model (written in TensorFlow version 2.1.0), like the Character Error Rate (CER) and Word Error Rate (WER), I created a callback to pass to the fit function of my model. It is able to generate the CER and WER at the end of an epoch.
It's my second choice as I wanted to create a custom metric for this, but you can only use keras backend functionality for custom metrics. Does anyone have any advice on how to convert the callback below into a Custom Metric (which can then be calculated during training on the validation and/or training data)?
Some roadblocks I encountered are:
Failure to convert the K.ctc_decode result to a sparse tensor
How can you calculate a distance like edit-distance using the Keras backend?
class Metrics(tf.keras.callbacks.Callback):
def __init__(self, valid_data, steps):
"""
valid_data is a TFRecordDataset with batches of 100 elements per batch, shuffled and repeated infinitely.
steps define the amount of batches per epoch
"""
super(Metrics, self).__init__()
self.valid_data = valid_data
self.steps = steps
def on_train_begin(self, logs={}):
self.cer = []
self.wer = []
def on_epoch_end(self, epoch, logs={}):
imgs = []
labels = []
for idx, (img, label) in enumerate(self.valid_data.as_numpy_iterator()):
if idx >= self.steps:
break
imgs.append(img)
labels.extend(label)
imgs = np.array(imgs)
labels = np.array(labels)
out = self.model.predict((batch for batch in imgs))
input_length = len(max(out, key=len))
out = np.asarray(out)
out_len = np.asarray([input_length for _ in range(len(out))])
decode, log = K.ctc_decode(out,
out_len,
greedy=True)
decode = [[[int(p) for p in x if p != -1] for x in y] for y in decode][0]
for (pred, lab) in zip(decode, labels):
dist = editdistance.eval(pred, lab)
self.cer.append(dist / (max(len(pred), len(lab))))
self.wer.append(not np.array_equal(pred, lab))
print("Mean CER: {}".format(np.mean([self.cer], axis=1)[0]))
print("Mean WER: {}".format(np.mean([self.wer], axis=1)[0]))
A:
Solved in TF 2.3.1, but should apply for previous versions of 2.x as well.
Some remarks:
Information on how to properly implement a Tensorflow Custom Metric is scarce. The question implied the use of a callback to implement the metric. This has longer epochs as a consequence (due to the explicit extra calculation of the metric on_epoch_end), or so I believe. Implementing it as a subclass of tensorflow.keras.metrics.Metric seems the right way, and yields results (if verbose is set correctly) while the epoch is ongoing.
Calculating the edit distance for the CER is quite easily performed using tf.edit_distance (using sparse tensors), this can subsequently be used to calculate the WER using some tf logic.
Alas, I am yet to find out how to implement both the CER and WER in one metric (as it has quite some duplicate code), if anyone knows how to do so, please contact me.
Custom metrics can simply be added into the compilation of your TF model:
self.model.compile(optimizer=opt, loss=loss, metrics=[CERMetric(), WERMetric()])
class CERMetric(tf.keras.metrics.Metric):
"""
A custom Keras metric to compute the Character Error Rate
"""
def __init__(self, name='CER_metric', **kwargs):
super(CERMetric, self).__init__(name=name, **kwargs)
self.cer_accumulator = self.add_weight(name="total_cer", initializer="zeros")
self.counter = self.add_weight(name="cer_count", initializer="zeros")
def update_state(self, y_true, y_pred, sample_weight=None):
input_shape = K.shape(y_pred)
input_length = tf.ones(shape=input_shape[0]) * K.cast(input_shape[1], 'float32')
decode, log = K.ctc_decode(y_pred,
input_length,
greedy=True)
decode = K.ctc_label_dense_to_sparse(decode[0], K.cast(input_length, 'int32'))
y_true_sparse = K.ctc_label_dense_to_sparse(y_true, K.cast(input_length, 'int32'))
decode = tf.sparse.retain(decode, tf.not_equal(decode.values, -1))
distance = tf.edit_distance(decode, y_true_sparse, normalize=True)
self.cer_accumulator.assign_add(tf.reduce_sum(distance))
self.counter.assign_add(len(y_true))
def result(self):
return tf.math.divide_no_nan(self.cer_accumulator, self.counter)
def reset_states(self):
self.cer_accumulator.assign(0.0)
self.counter.assign(0.0)
class WERMetric(tf.keras.metrics.Metric):
"""
A custom Keras metric to compute the Word Error Rate
"""
def __init__(self, name='WER_metric', **kwargs):
super(WERMetric, self).__init__(name=name, **kwargs)
self.wer_accumulator = self.add_weight(name="total_wer", initializer="zeros")
self.counter = self.add_weight(name="wer_count", initializer="zeros")
def update_state(self, y_true, y_pred, sample_weight=None):
input_shape = K.shape(y_pred)
input_length = tf.ones(shape=input_shape[0]) * K.cast(input_shape[1], 'float32')
decode, log = K.ctc_decode(y_pred,
input_length,
greedy=True)
decode = K.ctc_label_dense_to_sparse(decode[0], K.cast(input_length, 'int32'))
y_true_sparse = K.ctc_label_dense_to_sparse(y_true, K.cast(input_length, 'int32'))
decode = tf.sparse.retain(decode, tf.not_equal(decode.values, -1))
distance = tf.edit_distance(decode, y_true_sparse, normalize=True)
correct_words_amount = tf.reduce_sum(tf.cast(tf.not_equal(distance, 0), tf.float32))
self.wer_accumulator.assign_add(correct_words_amount)
self.counter.assign_add(len(y_true))
def result(self):
return tf.math.divide_no_nan(self.wer_accumulator, self.counter)
def reset_states(self):
self.wer_accumulator.assign(0.0)
self.counter.assign(0.0)
A:
Alas, I am yet to find out how to implement both the CER and WER in
one metric (as it has quite some duplicate code), if anyone knows how
to do so, please contact me.
Hey, this solution really helped me a lot. As of now, there are TensorFlow 2.10 releases, so for this version, I wrote a combination of WER and CER metrics, here is the final working code:
import tensorflow as tf
class CWERMetric(tf.keras.metrics.Metric):
""" A custom TensorFlow metric to compute the Character Error Rate
"""
def __init__(self, name='CWER', **kwargs):
super(CWERMetric, self).__init__(name=name, **kwargs)
self.cer_accumulator = tf.Variable(0.0, name="cer_accumulator", dtype=tf.float32)
self.wer_accumulator = tf.Variable(0.0, name="wer_accumulator", dtype=tf.float32)
self.counter = tf.Variable(0, name="counter", dtype=tf.int32)
def update_state(self, y_true, y_pred, sample_weight=None):
input_shape = tf.keras.backend.shape(y_pred)
input_length = tf.ones(shape=input_shape[0], dtype='int32') * tf.cast(input_shape[1], 'int32')
decode, log = tf.keras.backend.ctc_decode(y_pred, input_length, greedy=True)
decode = tf.keras.backend.ctc_label_dense_to_sparse(decode[0], input_length)
y_true_sparse = tf.cast(tf.keras.backend.ctc_label_dense_to_sparse(y_true, input_length), "int64")
decode = tf.sparse.retain(decode, tf.not_equal(decode.values, -1))
distance = tf.edit_distance(decode, y_true_sparse, normalize=True)
correct_words_amount = tf.reduce_sum(tf.cast(tf.not_equal(distance, 0), tf.float32))
self.wer_accumulator.assign_add(correct_words_amount)
self.cer_accumulator.assign_add(tf.reduce_sum(distance))
self.counter.assign_add(len(y_true))
def result(self):
return {
"CER": tf.math.divide_no_nan(self.cer_accumulator, tf.cast(self.counter, tf.float32)),
"WER": tf.math.divide_no_nan(self.wer_accumulator, tf.cast(self.counter, tf.float32))
}
I still need to check whether it calculates CER and WER correctly, I'll find out that something is missing, I'll update this.
|
Tensorflow Callback as Custom Metric for CTC
|
In an attempt to yield more metrics during the training of my model (written in TensorFlow version 2.1.0), like the Character Error Rate (CER) and Word Error Rate (WER), I created a callback to pass to the fit function of my model. It is able to generate the CER and WER at the end of an epoch.
It's my second choice as I wanted to create a custom metric for this, but you can only use keras backend functionality for custom metrics. Does anyone have any advice on how to convert the callback below into a Custom Metric (which can then be calculated during training on the validation and/or training data)?
Some roadblocks I encountered are:
Failure to convert the K.ctc_decode result to a sparse tensor
How can you calculate a distance like edit-distance using the Keras backend?
class Metrics(tf.keras.callbacks.Callback):
def __init__(self, valid_data, steps):
"""
valid_data is a TFRecordDataset with batches of 100 elements per batch, shuffled and repeated infinitely.
steps define the amount of batches per epoch
"""
super(Metrics, self).__init__()
self.valid_data = valid_data
self.steps = steps
def on_train_begin(self, logs={}):
self.cer = []
self.wer = []
def on_epoch_end(self, epoch, logs={}):
imgs = []
labels = []
for idx, (img, label) in enumerate(self.valid_data.as_numpy_iterator()):
if idx >= self.steps:
break
imgs.append(img)
labels.extend(label)
imgs = np.array(imgs)
labels = np.array(labels)
out = self.model.predict((batch for batch in imgs))
input_length = len(max(out, key=len))
out = np.asarray(out)
out_len = np.asarray([input_length for _ in range(len(out))])
decode, log = K.ctc_decode(out,
out_len,
greedy=True)
decode = [[[int(p) for p in x if p != -1] for x in y] for y in decode][0]
for (pred, lab) in zip(decode, labels):
dist = editdistance.eval(pred, lab)
self.cer.append(dist / (max(len(pred), len(lab))))
self.wer.append(not np.array_equal(pred, lab))
print("Mean CER: {}".format(np.mean([self.cer], axis=1)[0]))
print("Mean WER: {}".format(np.mean([self.wer], axis=1)[0]))
|
[
"Solved in TF 2.3.1, but should apply for previous versions of 2.x as well.\nSome remarks:\n\nInformation on how to properly implement a Tensorflow Custom Metric is scarce. The question implied the use of a callback to implement the metric. This has longer epochs as a consequence (due to the explicit extra calculation of the metric on_epoch_end), or so I believe. Implementing it as a subclass of tensorflow.keras.metrics.Metric seems the right way, and yields results (if verbose is set correctly) while the epoch is ongoing.\nCalculating the edit distance for the CER is quite easily performed using tf.edit_distance (using sparse tensors), this can subsequently be used to calculate the WER using some tf logic.\nAlas, I am yet to find out how to implement both the CER and WER in one metric (as it has quite some duplicate code), if anyone knows how to do so, please contact me.\nCustom metrics can simply be added into the compilation of your TF model:\nself.model.compile(optimizer=opt, loss=loss, metrics=[CERMetric(), WERMetric()])\n\nclass CERMetric(tf.keras.metrics.Metric):\n \"\"\"\n A custom Keras metric to compute the Character Error Rate\n \"\"\"\n def __init__(self, name='CER_metric', **kwargs):\n super(CERMetric, self).__init__(name=name, **kwargs)\n self.cer_accumulator = self.add_weight(name=\"total_cer\", initializer=\"zeros\")\n self.counter = self.add_weight(name=\"cer_count\", initializer=\"zeros\")\n\n def update_state(self, y_true, y_pred, sample_weight=None):\n input_shape = K.shape(y_pred)\n input_length = tf.ones(shape=input_shape[0]) * K.cast(input_shape[1], 'float32')\n\n decode, log = K.ctc_decode(y_pred,\n input_length,\n greedy=True)\n\n decode = K.ctc_label_dense_to_sparse(decode[0], K.cast(input_length, 'int32'))\n y_true_sparse = K.ctc_label_dense_to_sparse(y_true, K.cast(input_length, 'int32'))\n\n decode = tf.sparse.retain(decode, tf.not_equal(decode.values, -1))\n distance = tf.edit_distance(decode, y_true_sparse, normalize=True)\n\n self.cer_accumulator.assign_add(tf.reduce_sum(distance))\n self.counter.assign_add(len(y_true))\n\n def result(self):\n return tf.math.divide_no_nan(self.cer_accumulator, self.counter)\n\n def reset_states(self):\n self.cer_accumulator.assign(0.0)\n self.counter.assign(0.0)\n\nclass WERMetric(tf.keras.metrics.Metric):\n \"\"\"\n A custom Keras metric to compute the Word Error Rate\n \"\"\"\n def __init__(self, name='WER_metric', **kwargs):\n super(WERMetric, self).__init__(name=name, **kwargs)\n self.wer_accumulator = self.add_weight(name=\"total_wer\", initializer=\"zeros\")\n self.counter = self.add_weight(name=\"wer_count\", initializer=\"zeros\")\n\n def update_state(self, y_true, y_pred, sample_weight=None):\n input_shape = K.shape(y_pred)\n input_length = tf.ones(shape=input_shape[0]) * K.cast(input_shape[1], 'float32')\n\n decode, log = K.ctc_decode(y_pred,\n input_length,\n greedy=True)\n\n decode = K.ctc_label_dense_to_sparse(decode[0], K.cast(input_length, 'int32'))\n y_true_sparse = K.ctc_label_dense_to_sparse(y_true, K.cast(input_length, 'int32'))\n\n decode = tf.sparse.retain(decode, tf.not_equal(decode.values, -1))\n distance = tf.edit_distance(decode, y_true_sparse, normalize=True)\n \n correct_words_amount = tf.reduce_sum(tf.cast(tf.not_equal(distance, 0), tf.float32))\n\n self.wer_accumulator.assign_add(correct_words_amount)\n self.counter.assign_add(len(y_true))\n\n def result(self):\n return tf.math.divide_no_nan(self.wer_accumulator, self.counter)\n\n def reset_states(self):\n self.wer_accumulator.assign(0.0)\n self.counter.assign(0.0)\n\n\n",
"\nAlas, I am yet to find out how to implement both the CER and WER in\none metric (as it has quite some duplicate code), if anyone knows how\nto do so, please contact me.\n\nHey, this solution really helped me a lot. As of now, there are TensorFlow 2.10 releases, so for this version, I wrote a combination of WER and CER metrics, here is the final working code:\nimport tensorflow as tf\n\nclass CWERMetric(tf.keras.metrics.Metric):\n \"\"\" A custom TensorFlow metric to compute the Character Error Rate\n \"\"\"\n def __init__(self, name='CWER', **kwargs):\n super(CWERMetric, self).__init__(name=name, **kwargs)\n self.cer_accumulator = tf.Variable(0.0, name=\"cer_accumulator\", dtype=tf.float32)\n self.wer_accumulator = tf.Variable(0.0, name=\"wer_accumulator\", dtype=tf.float32)\n self.counter = tf.Variable(0, name=\"counter\", dtype=tf.int32)\n\n def update_state(self, y_true, y_pred, sample_weight=None):\n input_shape = tf.keras.backend.shape(y_pred)\n\n input_length = tf.ones(shape=input_shape[0], dtype='int32') * tf.cast(input_shape[1], 'int32')\n\n decode, log = tf.keras.backend.ctc_decode(y_pred, input_length, greedy=True)\n\n decode = tf.keras.backend.ctc_label_dense_to_sparse(decode[0], input_length)\n y_true_sparse = tf.cast(tf.keras.backend.ctc_label_dense_to_sparse(y_true, input_length), \"int64\")\n\n decode = tf.sparse.retain(decode, tf.not_equal(decode.values, -1))\n distance = tf.edit_distance(decode, y_true_sparse, normalize=True)\n\n correct_words_amount = tf.reduce_sum(tf.cast(tf.not_equal(distance, 0), tf.float32))\n\n self.wer_accumulator.assign_add(correct_words_amount)\n self.cer_accumulator.assign_add(tf.reduce_sum(distance))\n self.counter.assign_add(len(y_true))\n\n def result(self):\n return {\n \"CER\": tf.math.divide_no_nan(self.cer_accumulator, tf.cast(self.counter, tf.float32)),\n \"WER\": tf.math.divide_no_nan(self.wer_accumulator, tf.cast(self.counter, tf.float32))\n }\n\nI still need to check whether it calculates CER and WER correctly, I'll find out that something is missing, I'll update this.\n"
] |
[
1,
0
] |
[] |
[] |
[
"ctc",
"keras",
"python",
"tensorflow",
"tensorflow2.0"
] |
stackoverflow_0060285167_ctc_keras_python_tensorflow_tensorflow2.0.txt
|
Q:
How to define functions to ask for user input for months, year, and days (convert them to total year) and find simple interest
defining function and asking user input
def get_time(year, months, days):
year = int(input("enter year: "))
months = int(input("enter month: "))
days = int(input("enter days: "))
Hey everyone, thanks for the suggestions and advice, this is my first time using this site. Here is my problem:
The question is asking me to ask for user input for the year, months and days by using the input(). It also asks to return the total time in years. I know how to calculate the total time...
Ex:
If i have input 6 months it divides by 12 to get 0.5, if i input 73 days it divides by 365 to get 0.2. It then adds 0.5, 0.2 with user input for years (such as 2) and I get 2.7 years.
but I don't know how to put it into code. What I have so far is in the link above.
Thanks again
A:
def convertToYear():
year = float(input("Enter Year here YY: "))
month = float(input("Enter Month here MM: "))
day = float(input("Enter day here: "))
day = day/365
month = month/12
year = (month + day) + year
return year
def simpleInterest(timeInYears):
principal = float(input("Enter initial prinipal balance: "))
rate = float(input("Enter annual interest rate: "))
#using formula from google…
A = principal * (1 + (rate * timeInYears))
print("The final amount after %.2f" %timeInYears,"years is %.2f"%A)
return A
timeInYears = convertToYear()
print(simpleInterest(timeInYears))
|
How to define functions to ask for user input for months, year, and days (convert them to total year) and find simple interest
|
defining function and asking user input
def get_time(year, months, days):
year = int(input("enter year: "))
months = int(input("enter month: "))
days = int(input("enter days: "))
Hey everyone, thanks for the suggestions and advice, this is my first time using this site. Here is my problem:
The question is asking me to ask for user input for the year, months and days by using the input(). It also asks to return the total time in years. I know how to calculate the total time...
Ex:
If i have input 6 months it divides by 12 to get 0.5, if i input 73 days it divides by 365 to get 0.2. It then adds 0.5, 0.2 with user input for years (such as 2) and I get 2.7 years.
but I don't know how to put it into code. What I have so far is in the link above.
Thanks again
|
[
"def convertToYear():\n year = float(input(\"Enter Year here YY: \"))\n month = float(input(\"Enter Month here MM: \"))\n day = float(input(\"Enter day here: \"))\n day = day/365\n month = month/12\n year = (month + day) + year\n return year\n \n\ndef simpleInterest(timeInYears):\n principal = float(input(\"Enter initial prinipal balance: \"))\n rate = float(input(\"Enter annual interest rate: \"))\n #using formula from google…\n A = principal * (1 + (rate * timeInYears))\n print(\"The final amount after %.2f\" %timeInYears,\"years is %.2f\"%A)\n return A\n\n\n\ntimeInYears = convertToYear()\nprint(simpleInterest(timeInYears))\n\n"
] |
[
0
] |
[] |
[] |
[
"math",
"python"
] |
stackoverflow_0074583045_math_python.txt
|
Q:
How to import loopcontrol in jinja2
I need to use break for a for loop in jinja2.
Below is my code:
{% for i in range (0, desc) %}{{ desclist[i] }} {% set length = length + desclist[i]|length %}{% if length >= 70 %}{% break %}{% endif %}{% endfor %}
and to import the loopcontrol extension:
However, I got an error as followed:
jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'break'.
Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The
innermost block that needs to be closed is 'if'.
Any idea to make this work?
Thank you.
A:
Encountered the same issue, and realized on top of the document
it says:
The following example creates a Jinja environment with the i18n extension loaded:
jinja_env = Environment(extensions=['jinja2.ext.i18n'])
So I tried this and it finally resolved the error of ... Encountered unknown tag ...:
jinja_env = Environment(extensions=['jinja2.ext.loopcontrols'])
|
How to import loopcontrol in jinja2
|
I need to use break for a for loop in jinja2.
Below is my code:
{% for i in range (0, desc) %}{{ desclist[i] }} {% set length = length + desclist[i]|length %}{% if length >= 70 %}{% break %}{% endif %}{% endfor %}
and to import the loopcontrol extension:
However, I got an error as followed:
jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'break'.
Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The
innermost block that needs to be closed is 'if'.
Any idea to make this work?
Thank you.
|
[
"Encountered the same issue, and realized on top of the document\nit says:\n\nThe following example creates a Jinja environment with the i18n extension loaded:\njinja_env = Environment(extensions=['jinja2.ext.i18n'])\n\nSo I tried this and it finally resolved the error of ... Encountered unknown tag ...:\njinja_env = Environment(extensions=['jinja2.ext.loopcontrols'])\n"
] |
[
0
] |
[] |
[] |
[
"jinja2",
"python"
] |
stackoverflow_0036940435_jinja2_python.txt
|
Q:
Slice image in dynamic number of squares (grid) and save corner coordinates of those squares in list
I'm reading in an image with the Pillow library in Python. I want to "slice" it into squares, and save the corner coordinates of each of the squares in a list. For example in the image below, I would like to save the corner coordinates for square 15. (Top left corner is 0,0)
The first think I do after reading in the image is calculate the modulus of the height and width in pixels by the number of slices, and crop the image so the resulting number of pixels per square is the same and an integer.
from PIL import Image, ImageDraw, ImageFont
fileName = 'eyeImg_86.png'
img = Image.open(fileName)
vertical_slices = 8
horizontal_slices = 4
height = img.height
width = img.width
new_height = height - (height % horizontal_slices)
new_width = width - (width % vertical_slices)
img = img.crop((0, 0, new_width, new_height))
Then I calculate the size in pixels of each vertical and horizontal step.
horizontal_step = int(new_width / vertical_slices)
vertical_step = int(new_height / horizontal_slices)
And then I loop over the ranges between 0 to the total number of vertical and horizontal slices and append to a nested list (each inner list is a row)
points = []
for i in range(horizontal_slices+1):
row = []
for j in range(vertical_slices+1):
row.append((horizontal_step*j, vertical_step*i))
points.append(row)
Here's where I'm struggling to draw and to calculate what I need inside each of these squares. If I try to loop over all those points and draw them on the image.
with Image.open(fileName) as im:
im = im.convert(mode='RGB')
draw = ImageDraw.Draw(im)
for i in range(horizontal_slices+1):
if i < horizontal_slices:
for j in range(vertical_slices+1):
if j < vertical_slices:
draw.line([points[i][j], points[i+1][j-1]], fill=9999999)
Is there an easy way that I can dynamically give it the rows and columns and save each of the square coordinates to a list of tuples for example?
I'd like to both be able to draw them on top of the original image, and also calculate the number of black pixels inside each of the squares.
EDIT: To add some clarification, since the number of rows and columns of the grid is arbitrary, it will likely not be made of squares but rectangles. Furthermore, the numbering of these rectangles should be done row-wise from left to right, like reading.
Thank you
A:
There were (from my understanding) inconsistencies in your use of "horizontal/vertical"; I also removed the points list, since you can easily convert the rectangle number to its upper-left corner coords (see the function in the end); I draw the grid directly by drawing all horizontal lines and all vertical lines).
from PIL import Image, ImageDraw, ImageFont
fileName = 'test.png'
img = Image.open(fileName)
vertical_slices = 8
horizontal_slices = 6
height = img.height
width = img.width
new_height = height - (height % vertical_slices)
new_width = width - (width % horizontal_slices)
img = img.crop((0, 0, new_width, new_height))
horizontal_step = int(new_width / horizontal_slices)
vertical_step = int(new_height / vertical_slices)
# drawing the grid
img = img.convert(mode='RGB')
pix = img.load()
draw = ImageDraw.Draw(img)
for i in range(horizontal_slices+1):
draw.line([(i*horizontal_step,0), (i*horizontal_step,new_height)], fill=9999999)
for j in range(vertical_slices+1):
draw.line([(0,j*vertical_step), (new_width,j*vertical_step)], fill=9999999)
# with rectangles being numbered from 1 (upper left) to v_slices*h_slices (lower right) in reading order
def num_to_ul_corner_coords(num):
i = (num-1)%horizontal_slices
j = (num-1)//horizontal_slices
return(i*horizontal_step,j*vertical_step)
This should do what you want, provided your picture is pure black and white:
def count_black_pixels(num) :
cnt = 0
x, y = num_to_ul_corner_coords(num)
for i in range(horizontal_step):
for j in range(vertical_step):
if pix[x+i,y+j] == (0,0,0):
cnt += 1
perc = round(cnt/(horizontal_step*vertical_step)*100,2)
return cnt, perc
|
Slice image in dynamic number of squares (grid) and save corner coordinates of those squares in list
|
I'm reading in an image with the Pillow library in Python. I want to "slice" it into squares, and save the corner coordinates of each of the squares in a list. For example in the image below, I would like to save the corner coordinates for square 15. (Top left corner is 0,0)
The first think I do after reading in the image is calculate the modulus of the height and width in pixels by the number of slices, and crop the image so the resulting number of pixels per square is the same and an integer.
from PIL import Image, ImageDraw, ImageFont
fileName = 'eyeImg_86.png'
img = Image.open(fileName)
vertical_slices = 8
horizontal_slices = 4
height = img.height
width = img.width
new_height = height - (height % horizontal_slices)
new_width = width - (width % vertical_slices)
img = img.crop((0, 0, new_width, new_height))
Then I calculate the size in pixels of each vertical and horizontal step.
horizontal_step = int(new_width / vertical_slices)
vertical_step = int(new_height / horizontal_slices)
And then I loop over the ranges between 0 to the total number of vertical and horizontal slices and append to a nested list (each inner list is a row)
points = []
for i in range(horizontal_slices+1):
row = []
for j in range(vertical_slices+1):
row.append((horizontal_step*j, vertical_step*i))
points.append(row)
Here's where I'm struggling to draw and to calculate what I need inside each of these squares. If I try to loop over all those points and draw them on the image.
with Image.open(fileName) as im:
im = im.convert(mode='RGB')
draw = ImageDraw.Draw(im)
for i in range(horizontal_slices+1):
if i < horizontal_slices:
for j in range(vertical_slices+1):
if j < vertical_slices:
draw.line([points[i][j], points[i+1][j-1]], fill=9999999)
Is there an easy way that I can dynamically give it the rows and columns and save each of the square coordinates to a list of tuples for example?
I'd like to both be able to draw them on top of the original image, and also calculate the number of black pixels inside each of the squares.
EDIT: To add some clarification, since the number of rows and columns of the grid is arbitrary, it will likely not be made of squares but rectangles. Furthermore, the numbering of these rectangles should be done row-wise from left to right, like reading.
Thank you
|
[
"There were (from my understanding) inconsistencies in your use of \"horizontal/vertical\"; I also removed the points list, since you can easily convert the rectangle number to its upper-left corner coords (see the function in the end); I draw the grid directly by drawing all horizontal lines and all vertical lines).\nfrom PIL import Image, ImageDraw, ImageFont\nfileName = 'test.png'\nimg = Image.open(fileName)\n\nvertical_slices = 8\nhorizontal_slices = 6\n\nheight = img.height\nwidth = img.width\n\nnew_height = height - (height % vertical_slices)\nnew_width = width - (width % horizontal_slices)\n\nimg = img.crop((0, 0, new_width, new_height))\n\nhorizontal_step = int(new_width / horizontal_slices)\nvertical_step = int(new_height / vertical_slices)\n\n# drawing the grid\n\nimg = img.convert(mode='RGB')\npix = img.load()\n\ndraw = ImageDraw.Draw(img)\nfor i in range(horizontal_slices+1):\n draw.line([(i*horizontal_step,0), (i*horizontal_step,new_height)], fill=9999999)\nfor j in range(vertical_slices+1):\n draw.line([(0,j*vertical_step), (new_width,j*vertical_step)], fill=9999999)\n \n# with rectangles being numbered from 1 (upper left) to v_slices*h_slices (lower right) in reading order\n\ndef num_to_ul_corner_coords(num):\n i = (num-1)%horizontal_slices\n j = (num-1)//horizontal_slices\n return(i*horizontal_step,j*vertical_step)\n\nThis should do what you want, provided your picture is pure black and white:\ndef count_black_pixels(num) :\n cnt = 0\n x, y = num_to_ul_corner_coords(num)\n for i in range(horizontal_step):\n for j in range(vertical_step):\n if pix[x+i,y+j] == (0,0,0):\n cnt += 1\n\n perc = round(cnt/(horizontal_step*vertical_step)*100,2)\n\n return cnt, perc\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"python_imaging_library"
] |
stackoverflow_0074583095_python_python_imaging_library.txt
|
Q:
Python Flask Cors error - set according to documentation
I have created API using Flask in Python. Now I am trying to create front end, where I want to call API. I set CORS according Flask-Cors documentation, unfortunately it doesn't work.
from flask_cors import CORS
CORS(app)
I got this error
CORS error - Safari
CORS error - Chrome
I have found some similar topics, where was some solution. I have tried, but neither of them work for me. E.g.
CORS(app, origins=['http://localhost:4200'])
app.config['CORS_HEADERS'] = 'Content-Type'
I have also tried cross_origin decorator, but it doesn't work as well.
@app.route("/login", methods = ["POST"])
@cross_origin(origin='*')
def login():
credentials = request.get_json()
....
Could someone help me, how to solve this problem?
A:
Make sure the URL you are trying to access begins with 'http://' or 'https://' according to your web server's configuration
|
Python Flask Cors error - set according to documentation
|
I have created API using Flask in Python. Now I am trying to create front end, where I want to call API. I set CORS according Flask-Cors documentation, unfortunately it doesn't work.
from flask_cors import CORS
CORS(app)
I got this error
CORS error - Safari
CORS error - Chrome
I have found some similar topics, where was some solution. I have tried, but neither of them work for me. E.g.
CORS(app, origins=['http://localhost:4200'])
app.config['CORS_HEADERS'] = 'Content-Type'
I have also tried cross_origin decorator, but it doesn't work as well.
@app.route("/login", methods = ["POST"])
@cross_origin(origin='*')
def login():
credentials = request.get_json()
....
Could someone help me, how to solve this problem?
|
[
"Make sure the URL you are trying to access begins with 'http://' or 'https://' according to your web server's configuration\n"
] |
[
0
] |
[] |
[] |
[
"flask",
"python"
] |
stackoverflow_0074583218_flask_python.txt
|
Q:
Using yield to run code after method of function execution
I'm trying to create a class method that can run some code after its execution.
In pytest we have this functionality with fixtures:
@pytest.fixture
def db_connection(conn_str: str):
connection = psycopg2.connect(conn_str)
yield connection
connection.close() # this code will be executed after the test is done
Using this fixture in some test guarantees that connection will be closed soon after the test finishes. This behavior is described here, in the Teardown section.
When I try to do it in my own class methods, I didn't get the same result.
class Database:
def __call__(self, conn_str: str):
conn = psycopg2.connect(conn_str)
yield conn
print("Got here")
conn.close()
database = Database()
conn = next(database())
cur = conn.cursor()
cur.execute("select * from users")
result = cur.fetchall()
conn.commit()
result
The output is the data in users table, but I never see the "Got here" string, so I'm guessing this code after the yield keyword never runs.
Is there a way to achieve this?
A:
What you are trying to do is implement a context manager; the similarly to a Pytext fixture is incidental.
You can do this with contextmanager.contextlib
from contextlib import contextmanager
@contextmanager
def db_connection(conn_str):
connection = psycopg2.connect(conn_str)
yield connection
connection.close()
with db_connection(...) as db:
...
or define Database.__enter__ and Database.__exit__ explicitly:
class Database:
def __init__(self, conn_str: str):
self.conn_str = conn_str
def __enter__(self):
self.conn = psycopg2.connect(self.conn_str)
return self.conn
def __exit__(self, *args):
print("Got here")
self.conn.close()
with Database(...) as db:
...
(You can use the connection returned by psycopg2.connect as a context manager itself.)
A:
You need another next call to have it run the code after the yield:
database = Database()
gen = database() # Saved the generator to a variable
conn = next(gen)
cur = conn.cursor()
cur.execute("select * from users")
result = cur.fetchall()
conn.commit()
next(gen) # Triggers the latter part of the function
Also note, when you exhaust a generator, it raises a StopIteration exception as you'll see. You'll need to catch that as well.
|
Using yield to run code after method of function execution
|
I'm trying to create a class method that can run some code after its execution.
In pytest we have this functionality with fixtures:
@pytest.fixture
def db_connection(conn_str: str):
connection = psycopg2.connect(conn_str)
yield connection
connection.close() # this code will be executed after the test is done
Using this fixture in some test guarantees that connection will be closed soon after the test finishes. This behavior is described here, in the Teardown section.
When I try to do it in my own class methods, I didn't get the same result.
class Database:
def __call__(self, conn_str: str):
conn = psycopg2.connect(conn_str)
yield conn
print("Got here")
conn.close()
database = Database()
conn = next(database())
cur = conn.cursor()
cur.execute("select * from users")
result = cur.fetchall()
conn.commit()
result
The output is the data in users table, but I never see the "Got here" string, so I'm guessing this code after the yield keyword never runs.
Is there a way to achieve this?
|
[
"What you are trying to do is implement a context manager; the similarly to a Pytext fixture is incidental.\nYou can do this with contextmanager.contextlib\nfrom contextlib import contextmanager\n\n@contextmanager\ndef db_connection(conn_str):\n connection = psycopg2.connect(conn_str)\n yield connection\n connection.close()\n\nwith db_connection(...) as db:\n ...\n\nor define Database.__enter__ and Database.__exit__ explicitly:\nclass Database:\n def __init__(self, conn_str: str):\n self.conn_str = conn_str\n\n def __enter__(self):\n self.conn = psycopg2.connect(self.conn_str)\n return self.conn\n\n def __exit__(self, *args):\n print(\"Got here\")\n self.conn.close()\n\nwith Database(...) as db:\n ...\n\n(You can use the connection returned by psycopg2.connect as a context manager itself.)\n",
"You need another next call to have it run the code after the yield:\ndatabase = Database()\ngen = database() # Saved the generator to a variable\nconn = next(gen)\ncur = conn.cursor()\ncur.execute(\"select * from users\")\nresult = cur.fetchall()\nconn.commit()\nnext(gen) # Triggers the latter part of the function\n\nAlso note, when you exhaust a generator, it raises a StopIteration exception as you'll see. You'll need to catch that as well.\n"
] |
[
2,
1
] |
[] |
[] |
[
"generator",
"oop",
"psycopg2",
"pytest",
"python"
] |
stackoverflow_0074583333_generator_oop_psycopg2_pytest_python.txt
|
Q:
Exception in Tkinter callback with KEY ERROR
The below is my code with the name of abc.py and i am getting and error of type error on line 15. i don't know how to sort out the problem
The below is my code with the name of abc.py and i am getting and error of type error on line 15. i don't know how to sort out the problem
import tkinter as tk
from tkinter import ttk, messagebox
import mysql.connector
from tkinter import *
def GetValue(event):
e1.delete(0, END)
e2.delete(0, END)
e3.delete(0, END)
e4.delete(0, END)
e5.delete(0, END)
row_id = listBox.selection()[0]
select = listBox.set(row_id)
e1.insert(0,select['id'])
e2.insert(0,select['cname'])
e3.insert(0,select['cfname'])
e4.insert(0,select['ctype'])
e5.insert(0,select['coccupation'])
def Add():
cid = e1.get()
cnam = e2.get()
cfnam = e3.get()
ctyp = e4.get()
cocc = e4.get()
mysqldb=mysql.connector.connect(host="localhost",user="root",password="",database="criminal")
mycursor=mysqldb.cursor()
try:
sql = "INSERT INTO criminal (id,cname,cfname,ctype,coccupation) VALUES (%s, %s, %s, %s, %s)"
val = (cid,cnam,cfnam,ctyp,cocc)
mycursor.execute(sql, val)
mysqldb.commit()
lastid = mycursor.lastrowid
messagebox.showinfo("information", "Employee inserted successfully...")
e1.delete(0, END)
e2.delete(0, END)
e3.delete(0, END)
e4.delete(0, END)
e5.delete(0, END)
e1.focus_set()
except Exception as e:
print(e)
mysqldb.rollback()
mysqldb.close()
def update():
cid = e1.get()
cnam = e2.get()
cfnam = e3.get()
ctyp = e4.get()
cocc = e4.get()
mysqldb=mysql.connector.connect(host="localhost",user="root",password="",database="criminal")
mycursor=mysqldb.cursor()
try:
sql = "Update criminal set cname= %s,cfname= %s,ctype= %s,coccupation= %s where id= %s"
val = (cid,cnam,cfnam,ctyp,cocc)
mycursor.execute(sql, val)
mysqldb.commit()
lastid = mycursor.lastrowid
messagebox.showinfo("information", "Record Updateddddd successfully...")
e1.delete(0, END)
e2.delete(0, END)
e3.delete(0, END)
e4.delete(0, END)
e5.delete(0, END)
e1.focus_set()
except Exception as e:
print(e)
mysqldb.rollback()
mysqldb.close()
def delete():
cid = e1.get() mysqldb=mysql.connector.connect(host="localhost",user="root",password="",database="criminal")
mycursor=mysqldb.cursor()
try:
sql = "delete from criminal where id = %s"
val = (cid,)
mycursor.execute(sql, val)
mysqldb.commit()
lastid = mycursor.lastrowid
messagebox.showinfo("information", "Record Deleteeeee successfully...")
e1.delete(0, END)
e2.delete(0, END)
e3.delete(0, END)
e4.delete(0, END)
e5.delete(0, END)
e1.focus_set()
except Exception as e:
print(e)
mysqldb.rollback()
mysqldb.close()
def show():
mysqldb = mysql.connector.connect(host="localhost", user="root", password="", database="criminal")
mycursor = mysqldb.cursor()
mycursor.execute("SELECT id,cname,cfname,ctype,coccupation FROM criminal")
records = mycursor.fetchall()
print(records)
for i, (crid,crname, crfname,crtype,croccupation) in enumerate(records, start=1):
listBox.insert("", "end", values=(crid, crname, crfname, crtype, croccupation))
mysqldb.close()
root = Tk(className='Zohra & Team Criminal Management Software')
root['background']='#856ff8'
root.geometry("1200x500")
global e1
global e2
global e3
global e4
global e5
tk.Label(root, text="Criminal Management By zohra & Team", fg="Green",background="yellow" , font=(None, 30)).place(x=300, y=5)
tk.Label(root, text="Criminal ID",background="yellow",fg="green").place(x=10, y=10)
Label(root, text="Criminal Name",background="yellow").place(x=10, y=40)
Label(root, text="Criminal Father-Name",background="yellow").place(x=10, y=70)
Label(root, text="Criminal Type",background="yellow").place(x=10, y=100)
Label(root, text="Criminal Occupation",background="yellow").place(x=10, y=130)
e1 = Entry(root)
e1.place(x=140, y=10)
e2 = Entry(root)
e2.place(x=140, y=40)
e3 = Entry(root)
e3.place(x=140, y=70)
e4 = Entry(root)
e4.place(x=140, y=100)
e5 = Entry(root)
e5.place(x=140, y=130)
Button(root, text="Add",command = Add,height=3, width= 13).place(x=30, y=130)
Button(root, text="update",command = update,height=3, width= 13).place(x=140, y=130)
Button(root, text="Delete",command = delete,height=3, width= 13).place(x=250, y=130)
cols = ('Criminal id', 'Criminal Name', 'Criminal Father-Name', 'Criminal Type', 'Criminal Occupation')
listBox = ttk.Treeview(root, columns=cols, show='headings' )
for col in cols:
listBox.heading(col, text=col)
listBox.grid(row=1, column=0, columnspan=2)
listBox.place(x=10, y=200)
show()
listBox.bind('<Double-Button-1>',GetValue)
root.mainloop()
The below is key error message and i am not getting the solution for this
Error message:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\97150\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "abc.py", line 15, in GetValue
e1.insert(0,select['id'])
KeyError: 'id'
this is full code which i updated
A:
Since select is the result of listBox.set(row_id), it is a dictionary of column/value pairs for the selected item. The keys are then the column names of the treeview listBox instead of the column names from the database table:
def GetValue(event):
e1.delete(0, END)
e2.delete(0, END)
e3.delete(0, END)
e4.delete(0, END)
e5.delete(0, END)
row_id = listBox.selection()[0]
select = listBox.set(row_id)
e1.insert(0, select['Criminal id'])
e2.insert(0, select['Criminal Name'])
e3.insert(0, select['Criminal Father-Name'])
e4.insert(0, select['Criminal Type'])
e5.insert(0, select['Criminal Occupation'])
|
Exception in Tkinter callback with KEY ERROR
|
The below is my code with the name of abc.py and i am getting and error of type error on line 15. i don't know how to sort out the problem
The below is my code with the name of abc.py and i am getting and error of type error on line 15. i don't know how to sort out the problem
import tkinter as tk
from tkinter import ttk, messagebox
import mysql.connector
from tkinter import *
def GetValue(event):
e1.delete(0, END)
e2.delete(0, END)
e3.delete(0, END)
e4.delete(0, END)
e5.delete(0, END)
row_id = listBox.selection()[0]
select = listBox.set(row_id)
e1.insert(0,select['id'])
e2.insert(0,select['cname'])
e3.insert(0,select['cfname'])
e4.insert(0,select['ctype'])
e5.insert(0,select['coccupation'])
def Add():
cid = e1.get()
cnam = e2.get()
cfnam = e3.get()
ctyp = e4.get()
cocc = e4.get()
mysqldb=mysql.connector.connect(host="localhost",user="root",password="",database="criminal")
mycursor=mysqldb.cursor()
try:
sql = "INSERT INTO criminal (id,cname,cfname,ctype,coccupation) VALUES (%s, %s, %s, %s, %s)"
val = (cid,cnam,cfnam,ctyp,cocc)
mycursor.execute(sql, val)
mysqldb.commit()
lastid = mycursor.lastrowid
messagebox.showinfo("information", "Employee inserted successfully...")
e1.delete(0, END)
e2.delete(0, END)
e3.delete(0, END)
e4.delete(0, END)
e5.delete(0, END)
e1.focus_set()
except Exception as e:
print(e)
mysqldb.rollback()
mysqldb.close()
def update():
cid = e1.get()
cnam = e2.get()
cfnam = e3.get()
ctyp = e4.get()
cocc = e4.get()
mysqldb=mysql.connector.connect(host="localhost",user="root",password="",database="criminal")
mycursor=mysqldb.cursor()
try:
sql = "Update criminal set cname= %s,cfname= %s,ctype= %s,coccupation= %s where id= %s"
val = (cid,cnam,cfnam,ctyp,cocc)
mycursor.execute(sql, val)
mysqldb.commit()
lastid = mycursor.lastrowid
messagebox.showinfo("information", "Record Updateddddd successfully...")
e1.delete(0, END)
e2.delete(0, END)
e3.delete(0, END)
e4.delete(0, END)
e5.delete(0, END)
e1.focus_set()
except Exception as e:
print(e)
mysqldb.rollback()
mysqldb.close()
def delete():
cid = e1.get() mysqldb=mysql.connector.connect(host="localhost",user="root",password="",database="criminal")
mycursor=mysqldb.cursor()
try:
sql = "delete from criminal where id = %s"
val = (cid,)
mycursor.execute(sql, val)
mysqldb.commit()
lastid = mycursor.lastrowid
messagebox.showinfo("information", "Record Deleteeeee successfully...")
e1.delete(0, END)
e2.delete(0, END)
e3.delete(0, END)
e4.delete(0, END)
e5.delete(0, END)
e1.focus_set()
except Exception as e:
print(e)
mysqldb.rollback()
mysqldb.close()
def show():
mysqldb = mysql.connector.connect(host="localhost", user="root", password="", database="criminal")
mycursor = mysqldb.cursor()
mycursor.execute("SELECT id,cname,cfname,ctype,coccupation FROM criminal")
records = mycursor.fetchall()
print(records)
for i, (crid,crname, crfname,crtype,croccupation) in enumerate(records, start=1):
listBox.insert("", "end", values=(crid, crname, crfname, crtype, croccupation))
mysqldb.close()
root = Tk(className='Zohra & Team Criminal Management Software')
root['background']='#856ff8'
root.geometry("1200x500")
global e1
global e2
global e3
global e4
global e5
tk.Label(root, text="Criminal Management By zohra & Team", fg="Green",background="yellow" , font=(None, 30)).place(x=300, y=5)
tk.Label(root, text="Criminal ID",background="yellow",fg="green").place(x=10, y=10)
Label(root, text="Criminal Name",background="yellow").place(x=10, y=40)
Label(root, text="Criminal Father-Name",background="yellow").place(x=10, y=70)
Label(root, text="Criminal Type",background="yellow").place(x=10, y=100)
Label(root, text="Criminal Occupation",background="yellow").place(x=10, y=130)
e1 = Entry(root)
e1.place(x=140, y=10)
e2 = Entry(root)
e2.place(x=140, y=40)
e3 = Entry(root)
e3.place(x=140, y=70)
e4 = Entry(root)
e4.place(x=140, y=100)
e5 = Entry(root)
e5.place(x=140, y=130)
Button(root, text="Add",command = Add,height=3, width= 13).place(x=30, y=130)
Button(root, text="update",command = update,height=3, width= 13).place(x=140, y=130)
Button(root, text="Delete",command = delete,height=3, width= 13).place(x=250, y=130)
cols = ('Criminal id', 'Criminal Name', 'Criminal Father-Name', 'Criminal Type', 'Criminal Occupation')
listBox = ttk.Treeview(root, columns=cols, show='headings' )
for col in cols:
listBox.heading(col, text=col)
listBox.grid(row=1, column=0, columnspan=2)
listBox.place(x=10, y=200)
show()
listBox.bind('<Double-Button-1>',GetValue)
root.mainloop()
The below is key error message and i am not getting the solution for this
Error message:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\97150\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "abc.py", line 15, in GetValue
e1.insert(0,select['id'])
KeyError: 'id'
this is full code which i updated
|
[
"Since select is the result of listBox.set(row_id), it is a dictionary of column/value pairs for the selected item. The keys are then the column names of the treeview listBox instead of the column names from the database table:\ndef GetValue(event):\n e1.delete(0, END)\n e2.delete(0, END)\n e3.delete(0, END)\n e4.delete(0, END)\n e5.delete(0, END)\n row_id = listBox.selection()[0]\n select = listBox.set(row_id)\n e1.insert(0, select['Criminal id'])\n e2.insert(0, select['Criminal Name'])\n e3.insert(0, select['Criminal Father-Name'])\n e4.insert(0, select['Criminal Type'])\n e5.insert(0, select['Criminal Occupation'])\n\n"
] |
[
0
] |
[] |
[] |
[
"python",
"python_3.x",
"tkinter"
] |
stackoverflow_0074558178_python_python_3.x_tkinter.txt
|
Q:
How to solve the problem "TypeError: setEnabled(self, bool): argument 1 has unexpected type 'str'"?
I have encountered such a problem
`
> python .\main.py
Traceback (most recent call last):
File "C:\main.py", line 79, in writeF
self.ui.lineEdit.setEnabled(value)
TypeError: setEnabled(self, bool): argument 1 has unexpected type 'str'
`
My code is hosted on github, here's the repo link.
The relevant file part:
from PyQt5 import QtWidgets, QtCore
from design import Ui_MainWindow
import sys
class mywindow(QtWidgets.QMainWindow):
def __init__(self):
super(mywindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
#Здесь мы вносим изменения
'''self.ui.lineEdit.setPlaceholderText("ip address1")
self.ui.checkBox.stateChanged.connect(self.selected)
def selected(self):
value=True
if self.ui.checkBox.isChecked():
value=True
self.ui.label_result.clear()
else:
value=False
self.ui.label_result.setText("{}".format(self.ui.lineEdit.text()))
self.ui.lineEdit.setEnabled(value)'''
self.ui.lineEdit.setPlaceholderText("ip address1")
self.ui.lineEdit_2.setPlaceholderText("ip address2")
self.ui.lineEdit_3.setPlaceholderText("station name")
self.ui.lineEdit_4.setPlaceholderText("station number")
self.ui.lineEdit_5.setPlaceholderText("transmitter number")
self.ui.checkBox.stateChanged.connect(self.writeF)
def writeF(self):
#def replData(ip1, ip2, sName, sNumb, tNumb):
# список ключей, которые нужно будет заменить в файле template
keys=['_ip1_', '_ip2_', '_sName_', '_sNumb_', '_tNumb_']
#print(keys)
#Создаем список значений, на которые нужно будет заменить
values=[]
ip1 = self.ui.lineEdit.text()
ip2 = self.ui.lineEdit_2.text()
sName = self.ui.lineEdit_3.text()
sNumb = self.ui.lineEdit_4.text()
tNumb = self.ui.lineEdit_5.text()
values.append(ip1)
values.append(ip2)
values.append(sName)
values.append(sNumb)
values.append(tNumb)
#print(values)
#Создаем словарь. в качестве ключей (keys) это будут список значений, в
#котором надо будет заменить в файле template, а в качестве значений
#(values) - список значений, на которые нужно будет заменить
dictionary={}
for i in range(len(keys)):
dictionary[keys[i]] = values[i]
search_text = dictionary[keys[i]]
replace_text = keys[i]
#print(search_text)
#print(replace_text)
value=True
if self.ui.checkBox.isChecked():
value=True
#Считываем файл template, и меняем значения
with open(r'template.txt', 'r') as oFile:
rFile = oFile.read()
for key, val in dictionary.items():
rFile = rFile.replace(key, str(val))
#print(rFile)
#Запишем изменения в файл output
with open(r'output.txt', 'a') as wFile:
wFile.write('\n')
wFile.write('\n')
wFile.write('\n')
wFile.write(rFile)
self.ui.lineEdit.clear()
self.ui.lineEdit_2.clear()
self.ui.lineEdit_3.clear()
self.ui.lineEdit_4.clear()
self.ui.lineEdit_5.clear()
#else:
# value=False
# self.ui.label_result.setText("{}".format(self.ui.lineEdit.text()))
# self.ui.label_result.setText("{}".format(ip1))
self.ui.lineEdit.setEnabled(value)
'''
repeat="y"
while repeat == "y":
#ip1, ip2, sName, sNumb, tNumb = 1111, 2222, 3333, 4444, 5555
#ip1, ip2, sName, sNumb, tNumb = input("Enter the IP address1: "), input("Enter the IP address2: "), input("Enter the station name: "), input("Enter the station number: "), input("Enter the transmitter number: ")
replData(ip1, ip2, sName, sNumb, tNumb)
#Если нужно повторить:
repeat = input("Do you want to continue? (y/n): ")
if repeat == "n":
break
while (repeat!="y" and repeat!="n"):
repeat = input("Please enter the correct answer (y/n): ")
'''
app = QtWidgets.QApplication([])
application = mywindow()
application.show()
sys.exit(app.exec())
I'm starting to learn Python. I have developed a program that reads data from the user in the GUI via pyqt5 and qt designer, writes this data to a file output.txt. But I ran into a problem that gives an error in the command line, which I showed above. What did I do wrong
A:
Short Answer: You are overwriting the previously defined value of value in line 61.
Longer answer: Consider this minimized example:
value = True
dictionary = {'foo': 'bar', 'baz': 'qwurx'}
for key, value in dictionary.items():
print(key, value)
print(value, type(value))
Output:
# foo bar
# baz qwurx
# qwurx <class 'str'>
The issue is that you re-defined value in the loop on every call. The value-variable shadows and overwrites the outer one.
To find such things on your own next time: The error message is already a good hint. It tells you that the method expects a boolean value, but got a string instead. Now go back from the given line to find where the variable is set last...
Concerning coding style: Your code contains a lot of generic namings, like a dictionary called dictionary and variables called values. Think of more meaningful names to prevent such issues. See Clean Naming for further thoughts on this.
|
How to solve the problem "TypeError: setEnabled(self, bool): argument 1 has unexpected type 'str'"?
|
I have encountered such a problem
`
> python .\main.py
Traceback (most recent call last):
File "C:\main.py", line 79, in writeF
self.ui.lineEdit.setEnabled(value)
TypeError: setEnabled(self, bool): argument 1 has unexpected type 'str'
`
My code is hosted on github, here's the repo link.
The relevant file part:
from PyQt5 import QtWidgets, QtCore
from design import Ui_MainWindow
import sys
class mywindow(QtWidgets.QMainWindow):
def __init__(self):
super(mywindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
#Здесь мы вносим изменения
'''self.ui.lineEdit.setPlaceholderText("ip address1")
self.ui.checkBox.stateChanged.connect(self.selected)
def selected(self):
value=True
if self.ui.checkBox.isChecked():
value=True
self.ui.label_result.clear()
else:
value=False
self.ui.label_result.setText("{}".format(self.ui.lineEdit.text()))
self.ui.lineEdit.setEnabled(value)'''
self.ui.lineEdit.setPlaceholderText("ip address1")
self.ui.lineEdit_2.setPlaceholderText("ip address2")
self.ui.lineEdit_3.setPlaceholderText("station name")
self.ui.lineEdit_4.setPlaceholderText("station number")
self.ui.lineEdit_5.setPlaceholderText("transmitter number")
self.ui.checkBox.stateChanged.connect(self.writeF)
def writeF(self):
#def replData(ip1, ip2, sName, sNumb, tNumb):
# список ключей, которые нужно будет заменить в файле template
keys=['_ip1_', '_ip2_', '_sName_', '_sNumb_', '_tNumb_']
#print(keys)
#Создаем список значений, на которые нужно будет заменить
values=[]
ip1 = self.ui.lineEdit.text()
ip2 = self.ui.lineEdit_2.text()
sName = self.ui.lineEdit_3.text()
sNumb = self.ui.lineEdit_4.text()
tNumb = self.ui.lineEdit_5.text()
values.append(ip1)
values.append(ip2)
values.append(sName)
values.append(sNumb)
values.append(tNumb)
#print(values)
#Создаем словарь. в качестве ключей (keys) это будут список значений, в
#котором надо будет заменить в файле template, а в качестве значений
#(values) - список значений, на которые нужно будет заменить
dictionary={}
for i in range(len(keys)):
dictionary[keys[i]] = values[i]
search_text = dictionary[keys[i]]
replace_text = keys[i]
#print(search_text)
#print(replace_text)
value=True
if self.ui.checkBox.isChecked():
value=True
#Считываем файл template, и меняем значения
with open(r'template.txt', 'r') as oFile:
rFile = oFile.read()
for key, val in dictionary.items():
rFile = rFile.replace(key, str(val))
#print(rFile)
#Запишем изменения в файл output
with open(r'output.txt', 'a') as wFile:
wFile.write('\n')
wFile.write('\n')
wFile.write('\n')
wFile.write(rFile)
self.ui.lineEdit.clear()
self.ui.lineEdit_2.clear()
self.ui.lineEdit_3.clear()
self.ui.lineEdit_4.clear()
self.ui.lineEdit_5.clear()
#else:
# value=False
# self.ui.label_result.setText("{}".format(self.ui.lineEdit.text()))
# self.ui.label_result.setText("{}".format(ip1))
self.ui.lineEdit.setEnabled(value)
'''
repeat="y"
while repeat == "y":
#ip1, ip2, sName, sNumb, tNumb = 1111, 2222, 3333, 4444, 5555
#ip1, ip2, sName, sNumb, tNumb = input("Enter the IP address1: "), input("Enter the IP address2: "), input("Enter the station name: "), input("Enter the station number: "), input("Enter the transmitter number: ")
replData(ip1, ip2, sName, sNumb, tNumb)
#Если нужно повторить:
repeat = input("Do you want to continue? (y/n): ")
if repeat == "n":
break
while (repeat!="y" and repeat!="n"):
repeat = input("Please enter the correct answer (y/n): ")
'''
app = QtWidgets.QApplication([])
application = mywindow()
application.show()
sys.exit(app.exec())
I'm starting to learn Python. I have developed a program that reads data from the user in the GUI via pyqt5 and qt designer, writes this data to a file output.txt. But I ran into a problem that gives an error in the command line, which I showed above. What did I do wrong
|
[
"Short Answer: You are overwriting the previously defined value of value in line 61.\n\nLonger answer: Consider this minimized example:\nvalue = True\ndictionary = {'foo': 'bar', 'baz': 'qwurx'}\nfor key, value in dictionary.items():\n print(key, value)\nprint(value, type(value))\n\nOutput:\n# foo bar\n# baz qwurx\n# qwurx <class 'str'>\n\nThe issue is that you re-defined value in the loop on every call. The value-variable shadows and overwrites the outer one.\n\nTo find such things on your own next time: The error message is already a good hint. It tells you that the method expects a boolean value, but got a string instead. Now go back from the given line to find where the variable is set last...\n\nConcerning coding style: Your code contains a lot of generic namings, like a dictionary called dictionary and variables called values. Think of more meaningful names to prevent such issues. See Clean Naming for further thoughts on this.\n"
] |
[
-1
] |
[] |
[] |
[
"pyqt",
"pyqt5",
"python",
"qt",
"qt5"
] |
stackoverflow_0074581241_pyqt_pyqt5_python_qt_qt5.txt
|
Q:
Why isn't streamlit running in VScode?
I installed streamlit in VScode, and tried to run this.
import streamlit as st
st.title("Hello")
But I dont get streamlit to pop up in a new browser, instead I get this message in the terminal. Is this something to do with my files?
Warning: to view this Streamlit app on a browser, run it with the following
command:
streamlit run c:\Users\MyName\Documents\VS code\test.py [ARGUMENTS]
A:
Following the suggestion, just execute the streamlit run c:\Users\MyName\Documents\VS code\test.py in the terminal directly.
A:
There is a way to run Streamlit code in VSCode.
This enables utilizing the debugging features of VSCode.
Update the launch.json file with the following:
{
"configurations": [
{
"name": "Python:Streamlit",
"type": "python",
"request": "launch",
"module": "streamlit",
"args": [
"run",
"${file}"
]
}
]
}
Make sure the VSCode is configured with the right python environment.
A:
You probably aren't running VS Code from the Anaconda Navigator where streamlit is downloaded. Simply open VS Code from the Anaconda Navigator and it'll work or run conda activate base on terminal before running streamlit run app.py
A:
I've face the same issue. Then, solve it by following methods:
First you install properly streamlit package with pip install streamlit
then, go to terminal and run this
python -m streamlit run your_script.py
|
Why isn't streamlit running in VScode?
|
I installed streamlit in VScode, and tried to run this.
import streamlit as st
st.title("Hello")
But I dont get streamlit to pop up in a new browser, instead I get this message in the terminal. Is this something to do with my files?
Warning: to view this Streamlit app on a browser, run it with the following
command:
streamlit run c:\Users\MyName\Documents\VS code\test.py [ARGUMENTS]
|
[
"Following the suggestion, just execute the streamlit run c:\\Users\\MyName\\Documents\\VS code\\test.py in the terminal directly.\n",
"There is a way to run Streamlit code in VSCode.\nThis enables utilizing the debugging features of VSCode.\nUpdate the launch.json file with the following:\n\n{\n \"configurations\": [\n \n\n {\n \"name\": \"Python:Streamlit\",\n \"type\": \"python\",\n \"request\": \"launch\",\n \"module\": \"streamlit\",\n \n \"args\": [\n \n \"run\",\n \"${file}\"\n ]\n }\n ]\n}\n\n\n\nMake sure the VSCode is configured with the right python environment.\n",
"You probably aren't running VS Code from the Anaconda Navigator where streamlit is downloaded. Simply open VS Code from the Anaconda Navigator and it'll work or run conda activate base on terminal before running streamlit run app.py\n",
"I've face the same issue. Then, solve it by following methods:\n\nFirst you install properly streamlit package with pip install streamlit\nthen, go to terminal and run this\npython -m streamlit run your_script.py\n\n\n"
] |
[
1,
0,
0,
0
] |
[
"python -m streamlit run app.py\n\n"
] |
[
-1
] |
[
"python",
"streamlit",
"visual_studio_code"
] |
stackoverflow_0071917749_python_streamlit_visual_studio_code.txt
|
Q:
How to replace all list of list items with the index value of that list
I am trying to replace items in list of lists by the value of the index of that specific list. I can do it with a for loop, but I was wondering if there is a faster way to do this.
such that the following list
example = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
becomes:
solution = [[0, 0, 0], [1, 1, 1], [2, 2, 2]]
A:
Your way with for loop should work, but if you want another way in a short version then you can do it this way with list comprehension and enumerate,
example = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = [[index] * len(value) for index, value in enumerate(example)]
print(result)
A:
List comprehensions are usually faster than loops
Here is a solution with list comprehensions
example = [[1,2,3],[4,5,6],[7,8,9]]
solution = [[x for _ in range(len(example[x]))] for x in range(len(example))]
print(solution)
Output
[[0, 0, 0], [1, 1, 1], [2, 2, 2]]
A:
solution = [[i]*len(x) for i, x in enumerate(example)]
|
How to replace all list of list items with the index value of that list
|
I am trying to replace items in list of lists by the value of the index of that specific list. I can do it with a for loop, but I was wondering if there is a faster way to do this.
such that the following list
example = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
becomes:
solution = [[0, 0, 0], [1, 1, 1], [2, 2, 2]]
|
[
"Your way with for loop should work, but if you want another way in a short version then you can do it this way with list comprehension and enumerate,\nexample = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\nresult = [[index] * len(value) for index, value in enumerate(example)]\nprint(result)\n\n",
"List comprehensions are usually faster than loops\nHere is a solution with list comprehensions\nexample = [[1,2,3],[4,5,6],[7,8,9]]\nsolution = [[x for _ in range(len(example[x]))] for x in range(len(example))]\nprint(solution)\n\nOutput\n[[0, 0, 0], [1, 1, 1], [2, 2, 2]]\n\n",
"solution = [[i]*len(x) for i, x in enumerate(example)]\n\n"
] |
[
1,
0,
0
] |
[
"Here is a solution with the map function:\nres = list(map(lambda i : [i] * len(example[i]),\n range(len(example))\n ))\nprint(res)\n\nIt's more verbose than the comprehension method, but coming from other languages I prefer it - I find the map to be more explicit and easier to follow, as it's built out of the common components of higher-order functions rather than having its own syntax.\n"
] |
[
-1
] |
[
"list",
"python",
"replace"
] |
stackoverflow_0074583527_list_python_replace.txt
|
Q:
"Name 'x' is parameter and global" exception
I was wondering why this won't work? I'm fairly new to programming and I'm learning Python.
def convert(x,y):
while True:
try:
global x
x = int(input("Number: "))
except ValueError:
print("Make sure it is a number.")
while True:
try:
global y
y = int(input("Number: "))
except ValueError:
print("Make sure it is a number.")
convert(x,y)
Please tell me how to make this work.
Also, the error I get when I run this is name 'x' is parameter and global.
Ok, I fixed it. This is the correct code.
def convert():
while True:
try:
global number
number = int(input("Number: "))
break
except ValueError:
print("Make sure it is a number.")
while True:
try:
global number2
number2 = int(input("Number: "))
break
except ValueError:
print("Make sure it is a number.")
convert()
A:
In Python, parameters to functions (the things in parentheses next to the definition) are added as local variables to the scope of the function within the code. The Python interpreter makes a few major scans of your code. The first is a syntax scan in which it tests to see if your program is syntactically correct according to Python's rules. One of these rules is that, for a given block of code with its own scope, you can't have variables that are both in the local namespace and the global namespace.
In this scan, it does some special checks for you before even running the code. It stores the names of all global variables and local variables and checks them against one another. Since parameters to functions MUST be considered 'local' within the scope of the function, they cannot be declared as 'global' inside the function definition as that creates a contradiction.
What you could do is declare x and y to be global before your function definitions and that would work.
A:
Haidro explains the problem well, here is a solution!
You seem to want to read two values from the user, and save them to x and y. To do so, you can return multiple values from your function (python supports this).
Example:
def convert():
x = 0
y = 0
while True:
try:
x = int(input("Number: "))
break
except ValueError:
print("Make sure it is a number.")
while True:
try:
y = int(input("Number: "))
break
except ValueError:
print("Make sure it is a number.")
return x, y # magic
a, b = convert() # you could name these any way you want, even x/y, no collisions anymore
It would be better of course to clean up the code a little to remove the duplicated stuff:
def readNumber():
while True:
try:
x = int(input("Number: "))
return x
except ValueError:
print("Make sure it is a number!")
# and then
a = readNumber()
b = readNumber()
# or:
def convert():
return readNumber(), readNumber()
a, b = convert()
A:
It's because you're trying to override the parameter x, but you can't. Here's a related question
To fix this, don't name variables that. You're code is pretty much:
x = 'hi'
x = 5
print(x)
# Why isn't this 'hi'?
By the way, your while loops are going to be running indefinitely. After x = int(input("Number: ")), you may want to add a break. Same for the other loop.
A:
well, let's see the python3's API, Here are the description of the global key word:
The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.
Names listed in a global statement must not be used in the same code block textually preceding that global statement.
Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement.
Names listed in a global statement must not be defined as formal parameters
Names listed in a global statement must not be defined as formal parameters
Names listed in a global statement must not be defined as formal parameters
so, you can not name x and y both as formal parameters and as global
A:
So, if i'm right, to use global, the variable must not be in the function: fun([HERE]) and instead the brackets must be left empty !
Then we have to do global var and do whatever we need to do to it !
A:
I got the same error below:
SyntaxError: name 'num' is parameter and global
When I defined num global variable in test() which has num parameter as shown below:
num = 10
# Here
def test(num):
global num # Here
So, I removed num parameter from test() as shown below:
num = 10
# ↓↓ "num" is removed
def test():
global num
Or, I renamed num parameter to number parameter in test() as shown below:
num = 10
# ↓↓ "num" is renamed to "number"
def test(number):
global num
Then, the error was solved.
|
"Name 'x' is parameter and global" exception
|
I was wondering why this won't work? I'm fairly new to programming and I'm learning Python.
def convert(x,y):
while True:
try:
global x
x = int(input("Number: "))
except ValueError:
print("Make sure it is a number.")
while True:
try:
global y
y = int(input("Number: "))
except ValueError:
print("Make sure it is a number.")
convert(x,y)
Please tell me how to make this work.
Also, the error I get when I run this is name 'x' is parameter and global.
Ok, I fixed it. This is the correct code.
def convert():
while True:
try:
global number
number = int(input("Number: "))
break
except ValueError:
print("Make sure it is a number.")
while True:
try:
global number2
number2 = int(input("Number: "))
break
except ValueError:
print("Make sure it is a number.")
convert()
|
[
"In Python, parameters to functions (the things in parentheses next to the definition) are added as local variables to the scope of the function within the code. The Python interpreter makes a few major scans of your code. The first is a syntax scan in which it tests to see if your program is syntactically correct according to Python's rules. One of these rules is that, for a given block of code with its own scope, you can't have variables that are both in the local namespace and the global namespace.\nIn this scan, it does some special checks for you before even running the code. It stores the names of all global variables and local variables and checks them against one another. Since parameters to functions MUST be considered 'local' within the scope of the function, they cannot be declared as 'global' inside the function definition as that creates a contradiction. \nWhat you could do is declare x and y to be global before your function definitions and that would work.\n",
"Haidro explains the problem well, here is a solution!\nYou seem to want to read two values from the user, and save them to x and y. To do so, you can return multiple values from your function (python supports this).\nExample:\ndef convert():\n x = 0\n y = 0\n while True:\n try:\n x = int(input(\"Number: \"))\n break\n except ValueError:\n print(\"Make sure it is a number.\")\n while True:\n try:\n y = int(input(\"Number: \"))\n break\n except ValueError:\n print(\"Make sure it is a number.\")\n\n return x, y # magic \n\na, b = convert() # you could name these any way you want, even x/y, no collisions anymore\n\nIt would be better of course to clean up the code a little to remove the duplicated stuff:\ndef readNumber():\n while True:\n try:\n x = int(input(\"Number: \"))\n return x\n except ValueError:\n print(\"Make sure it is a number!\")\n\n# and then\na = readNumber()\nb = readNumber()\n\n# or:\ndef convert():\n return readNumber(), readNumber()\na, b = convert()\n\n",
"It's because you're trying to override the parameter x, but you can't. Here's a related question\nTo fix this, don't name variables that. You're code is pretty much:\nx = 'hi'\nx = 5\nprint(x)\n# Why isn't this 'hi'?\n\n\nBy the way, your while loops are going to be running indefinitely. After x = int(input(\"Number: \")), you may want to add a break. Same for the other loop.\n",
"well, let's see the python3's API, Here are the description of the global key word:\nThe global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.\nNames listed in a global statement must not be used in the same code block textually preceding that global statement.\nNames listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement.\nNames listed in a global statement must not be defined as formal parameters\nNames listed in a global statement must not be defined as formal parameters\nNames listed in a global statement must not be defined as formal parameters\nso, you can not name x and y both as formal parameters and as global\n",
"So, if i'm right, to use global, the variable must not be in the function: fun([HERE]) and instead the brackets must be left empty !\nThen we have to do global var and do whatever we need to do to it !\n",
"I got the same error below:\n\nSyntaxError: name 'num' is parameter and global\n\nWhen I defined num global variable in test() which has num parameter as shown below:\nnum = 10\n # Here\ndef test(num):\n global num # Here\n\nSo, I removed num parameter from test() as shown below:\nnum = 10\n # ↓↓ \"num\" is removed\ndef test():\n global num\n\nOr, I renamed num parameter to number parameter in test() as shown below:\nnum = 10\n # ↓↓ \"num\" is renamed to \"number\"\ndef test(number):\n global num\n\nThen, the error was solved.\n"
] |
[
12,
4,
3,
1,
1,
0
] |
[] |
[] |
[
"global_variables",
"parameters",
"python"
] |
stackoverflow_0018807749_global_variables_parameters_python.txt
|
Q:
Python loop to Comprehensive list
I'm new to Python Programming, this is my code;
myList = " Bob said, breakthrough study reveals that human and octopus brains have common features"
for word in myList.split():
if word[0] == "b":
print(word)
Can I simplify this code above to a list comprehension in Python?
Can't find the solution.
A:
Your existing approach seems OK to me but not sure if you want something like this or not with list comprehension. Note: your mylist name has a typo.
mylist = " Bob said, breakthrough study reveals that human and octopus brains have common features"
word = [word for word in mylist.split() if word[0] == "b"]
print(*word)
|
Python loop to Comprehensive list
|
I'm new to Python Programming, this is my code;
myList = " Bob said, breakthrough study reveals that human and octopus brains have common features"
for word in myList.split():
if word[0] == "b":
print(word)
Can I simplify this code above to a list comprehension in Python?
Can't find the solution.
|
[
"Your existing approach seems OK to me but not sure if you want something like this or not with list comprehension. Note: your mylist name has a typo.\nmylist = \" Bob said, breakthrough study reveals that human and octopus brains have common features\"\nword = [word for word in mylist.split() if word[0] == \"b\"]\nprint(*word)\n\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074583620_python.txt
|
Q:
how to create a flow generator in python for my custom data
I do a cat/dog binary classification
I created a training data this way, I applied an average filter to the images.
the problem is that the database is quite large and I get displayed right after that, your notebook tried to allocate more memory than is available. I read that generators in python take less disk memory and can solve this problem, but I don't know how to create a generator suitable for this code I just created as training data
train_dir = "../input/dog-cat/train"
CATEGORIES = ["dog", "cat"]
training_data = []
def create_training_data():
for category in CATEGORIES:
path = os.path.join(train_dir,category)
class_num = CATEGORIES.index(category)
for img in tqdm(os.listdir(path)):
try:
img_train = cv2.imread(os.path.join(path,img))
img_mean = cv2.blur(reduced_img_train,(9,9))
training_data.append([img_mean, class_num])
except Exception as e:
pass
create_training_data()
import random
random.shuffle(training_data)
x_train=[]
y_train=[]
for features,label in training_data:
x_train.append(features)
y_train.append(label)
A:
with the requirements you want to use ImageDataGenerator() with blur functions, check out CV2 CV2.blur(). You can do it by the provided custom function " preprocessing_function=custom_image_preprocess " parameter in ImageDataGenerator() itself.
Sample: CV2 using standard deviations when you can do it with a custom function or just the same image channels order ( one hidden technique for reconstructable data in the kickboxing colors game ).
import tensorflow as tf
import matplotlib.pyplot as plt
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
None
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
physical_devices = tf.config.experimental.list_physical_devices('GPU')
assert len(physical_devices) > 0, "Not enough GPU hardware devices available"
config = tf.config.experimental.set_memory_growth(physical_devices[0], True)
print(physical_devices)
print(config)
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
: Variables
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
BATCH_SIZE = 1
IMG_HEIGHT = 32
IMG_WIDTH = 32
IMG_CHANNELS=3
seed=42
directory = "F:\\datasets\\downloads\\example\\image\\"
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
: Definition / Class
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
def custom_image_preprocess( image ):
image = tf.keras.preprocessing.image.array_to_img(
image,
data_format=None,
scale=True
)
img_array = tf.keras.preprocessing.image.img_to_array( image )
img_1 = tf.keras.utils.array_to_img(img_array)
temp = tf.concat([ tf.constant( img_array[:,:,0], shape=(img_array.shape[0], img_array.shape[1], 1) ), tf.constant( 150 - img_array[:,:,1], shape=(img_array.shape[0], img_array.shape[1], 1) ) ], axis=2)
image = tf.concat([ tf.constant( temp[:,:,:], shape=(img_array.shape[0], img_array.shape[1], 2) ), tf.constant( 0.25 * img_array[:,:,2], shape=(img_array.shape[0], img_array.shape[1], 1) ) ], axis=2)
return image
def train_image_gen():
n_zoom_range = tf.where( tf.math.greater_equal( tf.constant( ( 1.0 * IMG_WIDTH ) / ( IMG_HEIGHT * 4 ), dtype=tf.float32 ), tf.constant( 0.25, dtype=tf.float32 ) ), ( 1.0 * IMG_WIDTH ) / ( IMG_HEIGHT * 4 ), 0.25 ).numpy()
n_rotation_range = tf.where( tf.math.greater_equal( tf.constant( ( 1.0 * IMG_WIDTH ) / ( IMG_HEIGHT * 4 ), dtype=tf.float32 ), tf.constant( 0.25, dtype=tf.float32 ) ), ( 1.0 * IMG_WIDTH ) / ( IMG_HEIGHT * 4 ) * 100, 27.25 ).numpy()
n_rescale = tf.where( tf.math.less_equal( tf.constant( 1.0 / ( IMG_WIDTH + IMG_HEIGHT )), tf.constant( 125.0 )), tf.constant( 1.0 / ( IMG_WIDTH + IMG_HEIGHT )).numpy(), 125.0 ).numpy()
train_generator = tf.keras.preprocessing.image.ImageDataGenerator(
# shear_range=0.2,
# zoom_range=float(n_zoom_range),
# horizontal_flip=True,
validation_split=0.2,
# rotation_range=float(n_rotation_range),
# rescale=float(n_rescale),
# rescale=1./255,
# featurewise_center=False,
# samplewise_center=False,
# featurewise_std_normalization=False,
# samplewise_std_normalization=False,
# zca_whitening=False,
# zca_epsilon=1e-06,
# rotation_range=0,
# width_shift_range=0.0,
# height_shift_range=0.0,
# brightness_range=None,
# shear_range=0.0,
# zoom_range=0.0,
# channel_shift_range=0.0,
# fill_mode='nearest',
# cval=0.0,
# horizontal_flip=False,
# vertical_flip=False,
# rescale=None,
preprocessing_function=custom_image_preprocess
# data_format=None,
# validation_split=0.0,
# interpolation_order=1,
# dtype=None
# https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator
)
train_image_ds = train_generator.flow_from_directory(
directory,
target_size=(IMG_HEIGHT, IMG_WIDTH),
batch_size=BATCH_SIZE,
class_mode='binary', # None # categorical # binary
subset='training',
color_mode='rgb', # rgb # grayscale
seed=seed,
)
return train_image_ds
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
: Model Initialize
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
model = tf.keras.models.Sequential([
tf.keras.layers.InputLayer(input_shape=( IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS )),
tf.keras.layers.Reshape((IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS)),
tf.keras.layers.RandomFlip('horizontal'),
tf.keras.layers.RandomRotation(0.2),
tf.keras.layers.Normalization(mean=3., variance=2.),
tf.keras.layers.Normalization(mean=4., variance=6.),
tf.keras.layers.Conv2D(32, (3, 3), activation='relu'),
tf.keras.layers.Reshape((30, 30, 32)),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Reshape((128, 225)),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(96, return_sequences=True, return_state=False)),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(96)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(192, activation='relu'),
tf.keras.layers.Dense(10),
])
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
: Optimizer
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
optimizer = tf.keras.optimizers.Nadam(
learning_rate=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-07,
name='Nadam'
) # 0.00001
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
: Loss Fn
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
lossfn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False)
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
: Model Summary
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
model.compile(optimizer=optimizer, loss=lossfn, metrics=['accuracy'])
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
: Training
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""
history = model.fit(train_image_gen(), validation_data=train_image_gen(), batch_size=100, epochs=50 )
input( '..;.' )
Output: Training with ImageGenerator, please monitor resources usages as the objective.
Found 16 images belonging to 2 classes.
Epoch 1/50
2022-11-26 23:00:06.112861: I tensorflow/stream_executor/cuda/cuda_dnn.cc:368] Loaded cuDNN version 8100
16/16 [==============================] - 9s 146ms/step - loss: 1.1202 - accuracy: 0.4375 - val_loss: 0.7060 - val_accuracy: 0.5000
Epoch 2/50
16/16 [==============================] - 1s 57ms/step - loss: 0.7892 - accuracy: 0.3125 - val_loss: 0.6961 - val_accuracy: 0.5000
Epoch 3/50
3/16 [====>.........................] - ETA: 0s - loss: 0.6903 - accuracy: 0.6667T
|
how to create a flow generator in python for my custom data
|
I do a cat/dog binary classification
I created a training data this way, I applied an average filter to the images.
the problem is that the database is quite large and I get displayed right after that, your notebook tried to allocate more memory than is available. I read that generators in python take less disk memory and can solve this problem, but I don't know how to create a generator suitable for this code I just created as training data
train_dir = "../input/dog-cat/train"
CATEGORIES = ["dog", "cat"]
training_data = []
def create_training_data():
for category in CATEGORIES:
path = os.path.join(train_dir,category)
class_num = CATEGORIES.index(category)
for img in tqdm(os.listdir(path)):
try:
img_train = cv2.imread(os.path.join(path,img))
img_mean = cv2.blur(reduced_img_train,(9,9))
training_data.append([img_mean, class_num])
except Exception as e:
pass
create_training_data()
import random
random.shuffle(training_data)
x_train=[]
y_train=[]
for features,label in training_data:
x_train.append(features)
y_train.append(label)
|
[
"with the requirements you want to use ImageDataGenerator() with blur functions, check out CV2 CV2.blur(). You can do it by the provided custom function \" preprocessing_function=custom_image_preprocess \" parameter in ImageDataGenerator() itself.\n\nSample: CV2 using standard deviations when you can do it with a custom function or just the same image channels order ( one hidden technique for reconstructable data in the kickboxing colors game ).\n\nimport tensorflow as tf\n\nimport matplotlib.pyplot as plt\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]\nNone\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nphysical_devices = tf.config.experimental.list_physical_devices('GPU')\nassert len(physical_devices) > 0, \"Not enough GPU hardware devices available\"\nconfig = tf.config.experimental.set_memory_growth(physical_devices[0], True)\nprint(physical_devices)\nprint(config)\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Variables\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nBATCH_SIZE = 1\nIMG_HEIGHT = 32\nIMG_WIDTH = 32\nIMG_CHANNELS=3\nseed=42\n\ndirectory = \"F:\\\\datasets\\\\downloads\\\\example\\\\image\\\\\"\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Definition / Class\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\ndef custom_image_preprocess( image ):\n image = tf.keras.preprocessing.image.array_to_img(\n image,\n data_format=None,\n scale=True\n )\n img_array = tf.keras.preprocessing.image.img_to_array( image )\n img_1 = tf.keras.utils.array_to_img(img_array)\n \n temp = tf.concat([ tf.constant( img_array[:,:,0], shape=(img_array.shape[0], img_array.shape[1], 1) ), tf.constant( 150 - img_array[:,:,1], shape=(img_array.shape[0], img_array.shape[1], 1) ) ], axis=2)\n image = tf.concat([ tf.constant( temp[:,:,:], shape=(img_array.shape[0], img_array.shape[1], 2) ), tf.constant( 0.25 * img_array[:,:,2], shape=(img_array.shape[0], img_array.shape[1], 1) ) ], axis=2)\n\n return image\n\n\ndef train_image_gen():\n\n n_zoom_range = tf.where( tf.math.greater_equal( tf.constant( ( 1.0 * IMG_WIDTH ) / ( IMG_HEIGHT * 4 ), dtype=tf.float32 ), tf.constant( 0.25, dtype=tf.float32 ) ), ( 1.0 * IMG_WIDTH ) / ( IMG_HEIGHT * 4 ), 0.25 ).numpy()\n n_rotation_range = tf.where( tf.math.greater_equal( tf.constant( ( 1.0 * IMG_WIDTH ) / ( IMG_HEIGHT * 4 ), dtype=tf.float32 ), tf.constant( 0.25, dtype=tf.float32 ) ), ( 1.0 * IMG_WIDTH ) / ( IMG_HEIGHT * 4 ) * 100, 27.25 ).numpy()\n n_rescale = tf.where( tf.math.less_equal( tf.constant( 1.0 / ( IMG_WIDTH + IMG_HEIGHT )), tf.constant( 125.0 )), tf.constant( 1.0 / ( IMG_WIDTH + IMG_HEIGHT )).numpy(), 125.0 ).numpy()\n\n train_generator = tf.keras.preprocessing.image.ImageDataGenerator(\n # shear_range=0.2,\n # zoom_range=float(n_zoom_range),\n # horizontal_flip=True,\n validation_split=0.2,\n # rotation_range=float(n_rotation_range),\n # rescale=float(n_rescale),\n \n # rescale=1./255,\n # featurewise_center=False,\n # samplewise_center=False,\n # featurewise_std_normalization=False,\n # samplewise_std_normalization=False,\n # zca_whitening=False,\n # zca_epsilon=1e-06,\n # rotation_range=0,\n # width_shift_range=0.0,\n # height_shift_range=0.0,\n # brightness_range=None,\n # shear_range=0.0,\n # zoom_range=0.0,\n # channel_shift_range=0.0,\n # fill_mode='nearest',\n # cval=0.0,\n # horizontal_flip=False,\n # vertical_flip=False,\n # rescale=None,\n preprocessing_function=custom_image_preprocess\n # data_format=None,\n # validation_split=0.0,\n # interpolation_order=1,\n # dtype=None\n # https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator\n \n )\n \n train_image_ds = train_generator.flow_from_directory(\n directory,\n target_size=(IMG_HEIGHT, IMG_WIDTH),\n batch_size=BATCH_SIZE,\n class_mode='binary', # None # categorical # binary\n subset='training',\n color_mode='rgb', # rgb # grayscale\n seed=seed,\n )\n \n return train_image_ds\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Model Initialize\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.InputLayer(input_shape=( IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS )),\n tf.keras.layers.Reshape((IMG_HEIGHT, IMG_WIDTH, IMG_CHANNELS)),\n tf.keras.layers.RandomFlip('horizontal'),\n tf.keras.layers.RandomRotation(0.2),\n tf.keras.layers.Normalization(mean=3., variance=2.),\n tf.keras.layers.Normalization(mean=4., variance=6.),\n tf.keras.layers.Conv2D(32, (3, 3), activation='relu'),\n tf.keras.layers.Reshape((30, 30, 32)),\n tf.keras.layers.MaxPooling2D((2, 2)),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Reshape((128, 225)),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(96, return_sequences=True, return_state=False)),\n tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(96)),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(192, activation='relu'),\n tf.keras.layers.Dense(10),\n])\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Optimizer\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\noptimizer = tf.keras.optimizers.Nadam(\n learning_rate=0.0001, beta_1=0.9, beta_2=0.999, epsilon=1e-07,\n name='Nadam'\n) # 0.00001\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Loss Fn\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" \nlossfn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False)\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Model Summary\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nmodel.compile(optimizer=optimizer, loss=lossfn, metrics=['accuracy'])\n\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n: Training\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\nhistory = model.fit(train_image_gen(), validation_data=train_image_gen(), batch_size=100, epochs=50 )\n\ninput( '..;.' )\n\n\nOutput: Training with ImageGenerator, please monitor resources usages as the objective.\n\nFound 16 images belonging to 2 classes.\nEpoch 1/50\n2022-11-26 23:00:06.112861: I tensorflow/stream_executor/cuda/cuda_dnn.cc:368] Loaded cuDNN version 8100\n16/16 [==============================] - 9s 146ms/step - loss: 1.1202 - accuracy: 0.4375 - val_loss: 0.7060 - val_accuracy: 0.5000\nEpoch 2/50\n16/16 [==============================] - 1s 57ms/step - loss: 0.7892 - accuracy: 0.3125 - val_loss: 0.6961 - val_accuracy: 0.5000\nEpoch 3/50\n 3/16 [====>.........................] - ETA: 0s - loss: 0.6903 - accuracy: 0.6667T\n\n\n\n"
] |
[
1
] |
[] |
[] |
[
"generator",
"image_processing",
"python",
"tensorflow",
"training_data"
] |
stackoverflow_0074581274_generator_image_processing_python_tensorflow_training_data.txt
|
Q:
Filtering a dataframe with the values of another dataframe
I have a bit of a complicated selecting in two dataframes.
Say I have a dataframe like this
country pop continent lifeExp gdpPercap
0 Afghanistan 31889923.0 Asia 43.828 974.580338
1 Albania 3600523.0 Europe 76.423 5937.029526
2 Algeria 33333216.0 Africa 72.301 6223.367465
(Actually this dataframe is product of a previous filtering I did)
And I have another dataframe like this
country year Production
Afghanistan 1980 20
Afghanistan 1981 10
Afghanistan 1983 5
Albania 1970 30
Albania 1980 40
Abisinia 1990 3
Algeria 1990 30
Angola 1980 2
Angola 1982 30
So what I want to get is the second dataframe but filtered with only the countries present in the first dataframe..(Afghanistan, Albania and Algeria)
What would be the best pythonic way to get this (hopefully in a fast operation)?
A:
You can use boolean indexing with pandas.DataFrame.loc and pandas.Series.isin :
out= df2.loc[df2["country"].isin(df1["country"])]
# Output :
print(out)
country year Production
0 Afghanistan 1980 20
1 Afghanistan 1981 10
2 Afghanistan 1983 5
3 Albania 1970 30
4 Albania 1980 40
6 Algeria 1990 30
|
Filtering a dataframe with the values of another dataframe
|
I have a bit of a complicated selecting in two dataframes.
Say I have a dataframe like this
country pop continent lifeExp gdpPercap
0 Afghanistan 31889923.0 Asia 43.828 974.580338
1 Albania 3600523.0 Europe 76.423 5937.029526
2 Algeria 33333216.0 Africa 72.301 6223.367465
(Actually this dataframe is product of a previous filtering I did)
And I have another dataframe like this
country year Production
Afghanistan 1980 20
Afghanistan 1981 10
Afghanistan 1983 5
Albania 1970 30
Albania 1980 40
Abisinia 1990 3
Algeria 1990 30
Angola 1980 2
Angola 1982 30
So what I want to get is the second dataframe but filtered with only the countries present in the first dataframe..(Afghanistan, Albania and Algeria)
What would be the best pythonic way to get this (hopefully in a fast operation)?
|
[
"You can use boolean indexing with pandas.DataFrame.loc and pandas.Series.isin :\nout= df2.loc[df2[\"country\"].isin(df1[\"country\"])]\n\n# Output :\nprint(out)\n\n country year Production\n0 Afghanistan 1980 20\n1 Afghanistan 1981 10\n2 Afghanistan 1983 5\n3 Albania 1970 30\n4 Albania 1980 40\n6 Algeria 1990 30\n\n"
] |
[
3
] |
[] |
[] |
[
"pandas",
"python"
] |
stackoverflow_0074583562_pandas_python.txt
|
Q:
Python: How to convert column with dictionary into columns
I have a DataFrame with a column that contains a dictionary as follows:
df:
date dictionary
0 2021-01-01 00:00:00 + 00:00 'Total':{'USD':100, 'size':20}, 'country':{'USA': {'income': 20000}, 'fees': {'total': 55}}
1 2021-01-01 00:00:00 + 00:00 'Total':{'EUR':200, 'size':40}, 'country':{'France': {'income': 10000}, 'fees': {'total': 30}}
1 2021-01-02 00:00:00 + 00:00 'Total':{'GBP':100, 'size':30}, 'country':{'UK': {'income': 23000}, 'fees': {'total': 24}}
What I want is to set USA as a column name and take the value of total from the fees and set that as the value, to get the following:
df_final:
date USA France UK
0 2021-01-01 00:00:00 + 00:00 55 30 NaN
1 2021-01-02 00:00:00 + 00:00 NaN NaN 24
My DataFrame has hundreds of columns. I have tried the following:
df_list = []
for idx, row in df.iterrows():
for dct in row['dictionary']:
dct['date'] = row['date']
df_list.append(dct)
But I get the following error: TypeError: 'str' object does not support item assignment. This happened specifically at dct['date'].
How can this be done?
EDIT: I added a few more rows to my DataFrame to better represent my problem.
A:
1)
The first possibility I see, is if your dataframe contains valid json strings like so:
df = pd.DataFrame({
'date': [
'2021-01-01 00:00:00',
'2021-01-01 00:00:00',
'2021-01-02 00:00:00',
],
'dictionary': [
'{"Total":{"USD":100, "size":20}, "country":{"USA": {"income": 20000}, "fees": {"total": 55}}}',
'{"Total":{"EUR":200, "size":40}, "country":{"France": {"income": 10000}, "fees": {"total": 30}}}',
'{"Total":{"GBP":100, "size":30}, "country":{"UK": {"income": 23000}, "fees": {"total": 24}}}',
]
})
df.date = pd.to_datetime(df.date)
df
Then you could do:
import json
for idx, row in df.iterrows():
dict = json.loads(row.dictionary)
dict_keys = list(dict["country"].keys())
df.loc[idx, dict_keys[0]] = dict["country"]["fees"]["total"]
df_final = df.groupby(df.date.dt.date) \
.agg('first') \
.drop(columns=['date', 'dictionary']) \
.reset_index()
df_final
2)
The second is if your df contained valid dictionaries like so:
df = pd.DataFrame({
'date': [
'2021-01-01 00:00:00',
'2021-01-01 00:00:00',
'2021-01-02 00:00:00',
],
'dictionary': [
{"Total":{"USD":100, "size":20}, "country":{"USA": {"income": 20000}, "fees": {"total": 55}}},
{"Total":{"EUR":200, "size":40}, "country":{"France": {"income": 10000}, "fees": {"total": 30}}},
{"Total":{"GBP":100, "size":30}, "country":{"UK": {"income": 23000}, "fees": {"total": 24}}},
]
})
df.date = pd.to_datetime(df.date)
df
Then you would:
import json
for idx, row in df.iterrows():
dict = row.dictionary
dict_keys = list(dict["country"].keys())
df.loc[idx, dict_keys[0]] = dict["country"]["fees"]["total"]
# df.loc[index, row]
df_final = df.groupby(df.date.dt.date) \
.agg('first') \
.drop(columns=['date', 'dictionary']) \
.reset_index()
df_final
A:
A possible solution:
aux = pd.json_normalize(df.dictionary, sep='_')
(aux.filter(like='income').loc[0]
.index.str.extract(r'.*_(.*)_.*').join(aux['country_fees_total']).join(df)
.pivot(index='date', columns=0, values='country_fees_total').reset_index()
.rename_axis(None, axis=1))
Output:
date France UK USA
0 2021-01-01 00:00:00 + 00:00 30.0 NaN 55.0
1 2021-01-02 00:00:00 + 00:00 NaN 24.0 NaN
|
Python: How to convert column with dictionary into columns
|
I have a DataFrame with a column that contains a dictionary as follows:
df:
date dictionary
0 2021-01-01 00:00:00 + 00:00 'Total':{'USD':100, 'size':20}, 'country':{'USA': {'income': 20000}, 'fees': {'total': 55}}
1 2021-01-01 00:00:00 + 00:00 'Total':{'EUR':200, 'size':40}, 'country':{'France': {'income': 10000}, 'fees': {'total': 30}}
1 2021-01-02 00:00:00 + 00:00 'Total':{'GBP':100, 'size':30}, 'country':{'UK': {'income': 23000}, 'fees': {'total': 24}}
What I want is to set USA as a column name and take the value of total from the fees and set that as the value, to get the following:
df_final:
date USA France UK
0 2021-01-01 00:00:00 + 00:00 55 30 NaN
1 2021-01-02 00:00:00 + 00:00 NaN NaN 24
My DataFrame has hundreds of columns. I have tried the following:
df_list = []
for idx, row in df.iterrows():
for dct in row['dictionary']:
dct['date'] = row['date']
df_list.append(dct)
But I get the following error: TypeError: 'str' object does not support item assignment. This happened specifically at dct['date'].
How can this be done?
EDIT: I added a few more rows to my DataFrame to better represent my problem.
|
[
"1)\nThe first possibility I see, is if your dataframe contains valid json strings like so:\ndf = pd.DataFrame({\n 'date': [\n '2021-01-01 00:00:00', \n '2021-01-01 00:00:00',\n '2021-01-02 00:00:00', \n ],\n 'dictionary': [ \n '{\"Total\":{\"USD\":100, \"size\":20}, \"country\":{\"USA\": {\"income\": 20000}, \"fees\": {\"total\": 55}}}',\n '{\"Total\":{\"EUR\":200, \"size\":40}, \"country\":{\"France\": {\"income\": 10000}, \"fees\": {\"total\": 30}}}',\n '{\"Total\":{\"GBP\":100, \"size\":30}, \"country\":{\"UK\": {\"income\": 23000}, \"fees\": {\"total\": 24}}}',\n ]\n})\n\ndf.date = pd.to_datetime(df.date)\ndf\n\n\nThen you could do:\nimport json\n\nfor idx, row in df.iterrows():\n dict = json.loads(row.dictionary)\n dict_keys = list(dict[\"country\"].keys())\n df.loc[idx, dict_keys[0]] = dict[\"country\"][\"fees\"][\"total\"]\n\ndf_final = df.groupby(df.date.dt.date) \\\n .agg('first') \\\n .drop(columns=['date', 'dictionary']) \\\n .reset_index()\n \ndf_final\n\n\n2)\nThe second is if your df contained valid dictionaries like so:\ndf = pd.DataFrame({\n 'date': [\n '2021-01-01 00:00:00', \n '2021-01-01 00:00:00',\n '2021-01-02 00:00:00', \n ],\n 'dictionary': [ \n {\"Total\":{\"USD\":100, \"size\":20}, \"country\":{\"USA\": {\"income\": 20000}, \"fees\": {\"total\": 55}}},\n {\"Total\":{\"EUR\":200, \"size\":40}, \"country\":{\"France\": {\"income\": 10000}, \"fees\": {\"total\": 30}}},\n {\"Total\":{\"GBP\":100, \"size\":30}, \"country\":{\"UK\": {\"income\": 23000}, \"fees\": {\"total\": 24}}},\n ]\n})\n\ndf.date = pd.to_datetime(df.date)\ndf\n\n\nThen you would:\nimport json\n\nfor idx, row in df.iterrows():\n dict = row.dictionary\n dict_keys = list(dict[\"country\"].keys())\n df.loc[idx, dict_keys[0]] = dict[\"country\"][\"fees\"][\"total\"]\n # df.loc[index, row]\n\ndf_final = df.groupby(df.date.dt.date) \\\n .agg('first') \\\n .drop(columns=['date', 'dictionary']) \\\n .reset_index()\n\ndf_final\n\n\n",
"A possible solution:\naux = pd.json_normalize(df.dictionary, sep='_')\n(aux.filter(like='income').loc[0]\n .index.str.extract(r'.*_(.*)_.*').join(aux['country_fees_total']).join(df)\n .pivot(index='date', columns=0, values='country_fees_total').reset_index()\n .rename_axis(None, axis=1))\n\nOutput:\n date France UK USA\n0 2021-01-01 00:00:00 + 00:00 30.0 NaN 55.0\n1 2021-01-02 00:00:00 + 00:00 NaN 24.0 NaN\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"dataframe",
"dictionary",
"list",
"pandas",
"python"
] |
stackoverflow_0074577324_dataframe_dictionary_list_pandas_python.txt
|
Q:
Why is Python saying modules are imported when they are not?
Python 3.6.5
Using this answer as a guide, I attempted to see whether some modules, such as math were imported.
But Python tells me they are all imported when they are not.
>>> import sys
>>> 'math' in sys.modules
True
>>> 'math' not in sys.modules
False
>>> math.pi
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined
>>> import math
>>> 'math' in sys.modules
True
>>> math.pi
3.141592653589793
A:
to explain this, let's define this function:
def import_math():
import math
import_math()
the above function will import the module math, but only in its local scope, anyone that tries to reference math outside of it will get a name error, because math is not defined in the global scope.
any module that is imported is saved into sys.modules so a call to check
import_math()
print("math" in sys.modules)
will print True, because sys.modules caches any module that is loaded anywhere, whether or not it was available in the global scope, a very simple way to define math in the global scope would then to
import_math()
math = sys.modules["math"]
which will convert it from being only in sys.modules to being in the global scope, this is just equivalent to
import math
which defines a variable math in the global scope that points to the module math.
now if you want to see whether "math" exists in the global scope is to check if it is in the global scope directly.
print("math" in globals())
print("math" in locals())
which will print false if "math" wasn't imported into the global or local scope and is therefore inaccessable.
|
Why is Python saying modules are imported when they are not?
|
Python 3.6.5
Using this answer as a guide, I attempted to see whether some modules, such as math were imported.
But Python tells me they are all imported when they are not.
>>> import sys
>>> 'math' in sys.modules
True
>>> 'math' not in sys.modules
False
>>> math.pi
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined
>>> import math
>>> 'math' in sys.modules
True
>>> math.pi
3.141592653589793
|
[
"to explain this, let's define this function:\ndef import_math():\n import math\n\nimport_math()\n\nthe above function will import the module math, but only in its local scope, anyone that tries to reference math outside of it will get a name error, because math is not defined in the global scope.\nany module that is imported is saved into sys.modules so a call to check\nimport_math()\nprint(\"math\" in sys.modules)\n\nwill print True, because sys.modules caches any module that is loaded anywhere, whether or not it was available in the global scope, a very simple way to define math in the global scope would then to\nimport_math()\nmath = sys.modules[\"math\"]\n\nwhich will convert it from being only in sys.modules to being in the global scope, this is just equivalent to\nimport math\n\nwhich defines a variable math in the global scope that points to the module math.\nnow if you want to see whether \"math\" exists in the global scope is to check if it is in the global scope directly.\nprint(\"math\" in globals())\nprint(\"math\" in locals())\n\nwhich will print false if \"math\" wasn't imported into the global or local scope and is therefore inaccessable.\n"
] |
[
8
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074583630_python.txt
|
Q:
"IndentationError: unindent does not match any outer indentation level" after try block
So I get this error when I run the program. The error is supposed to be at line 11 after the 'try' block but that's exactly how the author of the book I use for learning python displayed it. Can someone help me?
print("Give me two number, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
if second_number == 'q':
break
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print(answer)
I wanted it to work but it didn't.
A:
There was an issue with the indentation from line 11 onwards. It was 1 extra space to the right compared to the code above it. I suggest you use an IDE like PyCharm or VSCode (both for free), since it will help you a lot in finding not just such bugs but even harder to detect, like default mutable argument.
Personally, I am familiar with PyCharm, where you should use Tab to change indentation (it actually converts it to 4 spaces; never mix Tab with white-space).
If you have any other question let me know :)
print("Give me two number, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
if second_number == 'q':
break
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print(answer)
|
"IndentationError: unindent does not match any outer indentation level" after try block
|
So I get this error when I run the program. The error is supposed to be at line 11 after the 'try' block but that's exactly how the author of the book I use for learning python displayed it. Can someone help me?
print("Give me two number, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
if second_number == 'q':
break
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print(answer)
I wanted it to work but it didn't.
|
[
"There was an issue with the indentation from line 11 onwards. It was 1 extra space to the right compared to the code above it. I suggest you use an IDE like PyCharm or VSCode (both for free), since it will help you a lot in finding not just such bugs but even harder to detect, like default mutable argument.\nPersonally, I am familiar with PyCharm, where you should use Tab to change indentation (it actually converts it to 4 spaces; never mix Tab with white-space).\nIf you have any other question let me know :)\nprint(\"Give me two number, and I'll divide them.\")\nprint(\"Enter 'q' to quit.\")\n\nwhile True:\n first_number = input(\"\\nFirst number: \")\n if first_number == 'q':\n break\n second_number = input(\"Second number: \")\n if second_number == 'q':\n break\n try:\n answer = int(first_number) / int(second_number)\n except ZeroDivisionError:\n print(\"You can't divide by zero!\")\n else:\n print(answer)\n\n"
] |
[
0
] |
[
"Your try block is 1 space to the right with respect to the previous indent:\nwhile True:\n first_number = input(\"\\nFirst number: \")\n if first_number == 'q':\n break\n second_number = input(\"Second number: \")\n if second_number == 'q':\n break\n try:\n answer = int(first_number) / int(second_number)\n except ZeroDivisionError:\n print(\"You can't divide by zero!\")\n else:\n print(answer)\n\nAlways configure your text editor or IDE to replace tabs with 4 spaces to avoid these issues and keep your Python code aligned with this indentation size.\n"
] |
[
-1
] |
[
"indentation",
"python",
"try_except"
] |
stackoverflow_0074583683_indentation_python_try_except.txt
|
Q:
Keep Selenium Webdriver across Celery Tasks
I developed a Flask web app that uses Celery to handle tasks. One of these tasks consists of scraping a bunch of pages (around 200) using a custom Class derived from a selenium chrome driver.
@celery_app.task
def scrape_async():
driver = MyDriver(exec_path=os.environ.get('CHROMEDRIVER_PATH'), options=some_chrome_options)
# Update 'urls_to_scrape' attribute by finding the urls to scrape from a main url
driver.find_urls_to_scrape_from_main_url()
# Loop over each page and store the data in database
for url in driver.urls_to_scrape:
driver.scrape_page(url)
# Exit driver
driver.quit()
This worked well both in local and in production until the number of pages to scrape increased. I received a memory usage error on Heroku and realized how memory intensive the task was.
After some research, I found out that it would be easier to use a subtask in my loop (i.e. running this subtask for each page), as described below.
@celery_app.task
def subtask(url):
driver.scrape_page(url)
@celery_app.task
def scrape_async():
driver = MyDriver(exec_path=os.environ.get('CHROMEDRIVER_PATH'), options=some_chrome_options)
# Update 'urls_to_scrape' attribute by finding the urls to scrape from a main url
driver.find_urls_to_scrape_from_main_url()
# Loop over each page and store the data in database
for url in driver.urls_to_scrape:
subtask.delay(url)
# Exit driver
driver.quit()
My concern is about how to keep the driver object between the main task and the subtask.
I found this link, on how to instantiate Task but I couldn't manage to create one driver across multiple tasks.
Any idea on how to proceed to achieve my goal?
Thank you
A:
One approach would be to use a selenium grid if you are using distributed crawling by doing so you will reduce the amount of resource usage for loading, rendering htmls, executing the js script to other server.
And in doing so you dont need to bother about the stuffs to be picked by the worker if you are using tasks backend if you are crawling nested links, multiple nested pages can be crawled by multiple workers independently and required mata data can be passed using results backend with group chains and chords functionality in celery.
|
Keep Selenium Webdriver across Celery Tasks
|
I developed a Flask web app that uses Celery to handle tasks. One of these tasks consists of scraping a bunch of pages (around 200) using a custom Class derived from a selenium chrome driver.
@celery_app.task
def scrape_async():
driver = MyDriver(exec_path=os.environ.get('CHROMEDRIVER_PATH'), options=some_chrome_options)
# Update 'urls_to_scrape' attribute by finding the urls to scrape from a main url
driver.find_urls_to_scrape_from_main_url()
# Loop over each page and store the data in database
for url in driver.urls_to_scrape:
driver.scrape_page(url)
# Exit driver
driver.quit()
This worked well both in local and in production until the number of pages to scrape increased. I received a memory usage error on Heroku and realized how memory intensive the task was.
After some research, I found out that it would be easier to use a subtask in my loop (i.e. running this subtask for each page), as described below.
@celery_app.task
def subtask(url):
driver.scrape_page(url)
@celery_app.task
def scrape_async():
driver = MyDriver(exec_path=os.environ.get('CHROMEDRIVER_PATH'), options=some_chrome_options)
# Update 'urls_to_scrape' attribute by finding the urls to scrape from a main url
driver.find_urls_to_scrape_from_main_url()
# Loop over each page and store the data in database
for url in driver.urls_to_scrape:
subtask.delay(url)
# Exit driver
driver.quit()
My concern is about how to keep the driver object between the main task and the subtask.
I found this link, on how to instantiate Task but I couldn't manage to create one driver across multiple tasks.
Any idea on how to proceed to achieve my goal?
Thank you
|
[
"One approach would be to use a selenium grid if you are using distributed crawling by doing so you will reduce the amount of resource usage for loading, rendering htmls, executing the js script to other server.\nAnd in doing so you dont need to bother about the stuffs to be picked by the worker if you are using tasks backend if you are crawling nested links, multiple nested pages can be crawled by multiple workers independently and required mata data can be passed using results backend with group chains and chords functionality in celery.\n"
] |
[
0
] |
[] |
[] |
[
"celery",
"python",
"selenium",
"selenium_chromedriver"
] |
stackoverflow_0065656175_celery_python_selenium_selenium_chromedriver.txt
|
Q:
sum elements in python list if match condition
I have a variable with lists with varied number of elements:
['20', 'M', '10', 'M', '1', 'D', '14', 'M', '106', 'M']
['124', 'M', '19', 'M', '7', 'M']
['19', 'M', '131', 'M']
['3', 'M', '19', 'M', '128', 'M']
['12', 'M', '138', 'M']
Variable is always number, letter and order matters.
I would to add the values only of consecutive Ms to be (i.e. if there is a D, skip the sum):
['30', 'M', '1', 'D', '120', 'M']
['150', 'M']
['150', 'M']
['150', 'M']
['150', 'M']
ps. the complete story is that I want to convert soft clips to match in a bam file, but got stuck in that step.
#!/usr/bin/python
import sys
import pysam
bamFile = sys.argv[1];
bam = pysam.AlignmentFile(bamFile, 'rb')
for read in bam:
cigar=read.cigarstring
sepa = re.findall('(\d+|[A-Za-z]+)', cigar)
for i in range(len(sepa)):
if sepa[i] == 'S':
sepa[i] = 'M'
A:
You can slice Python lists using a step (sometimes called a stride), you can use this to get every second element, starting at index 1 (for the first letter):
>>> example = ['30', 'M', '1', 'D', '120', 'M']
>>> example[1::2]
['M', 'D', 'M']
The [1::2] syntax means: start at index 1, go on until you run out of elements (nothing entered between the : delimiters), and step over the list to return every second value.
You can do the same thing for the numbers, using [::2], so begin with the value right at the start and take every other value.
If you then combine this with the zip() function you can pair up your numbers and letters to figure out what to sum:
def sum_m_values(values):
summed = []
m_sum = 0
for number, letter in zip(values[::2], values[1::2]):
if letter != "M":
if m_sum:
summed += (str(m_sum), "M")
m_sum = 0
summed += (number, letter)
else:
m_sum += int(number)
if m_sum:
summed += (str(m_sum), "M")
return summed
The above function takes your list of numbers and letters and:
creates a list for the results
tracks a running sum of "M" values
pairs up the numbers and letters
for each pair:
if it is a number and "M", add that value (as an integer) to the running sum.
otherwise, adds the running sum (if any) to the list with the letter "M", then adds the current number and letter too.
after all pairs are processed, adds the running sum and the letter "M", if there is any.
This covers all your example inputs:
>>> def sum_m_values(values):
... summed = []
... m_sum = 0
... for number, letter in zip(values[::2], values[1::2]):
... if letter != "M":
... if m_sum:
... summed += (str(m_sum), "M")
... m_sum = 0
... summed += (number, letter)
... else:
... m_sum += int(number)
... if m_sum:
... summed += (str(m_sum), "M")
... return summed
...
>>> examples = [
... ['20', 'M', '10', 'M', '1', 'D', '14', 'M', '106', 'M'],
... ['124', 'M', '19', 'M', '7', 'M'],
... ['19', 'M', '131', 'M'],
... ['3', 'M', '19', 'M', '128', 'M'],
... ['12', 'M', '138', 'M'],
... ]
>>> for example in examples:
... print(example, "->", sum_m_values(example))
...
['20', 'M', '10', 'M', '1', 'D', '14', 'M', '106', 'M'] -> ['30', 'M', '1', 'D', '120', 'M']
['124', 'M', '19', 'M', '7', 'M'] -> ['150', 'M']
['19', 'M', '131', 'M'] -> ['150', 'M']
['3', 'M', '19', 'M', '128', 'M'] -> ['150', 'M']
['12', 'M', '138', 'M'] -> ['150', 'M']
There are other methods of looping over a list in fixed-sized groups; you can also create an iterator for the list with iter()and then use zip() to pull in consecutive elements into pairs:
it = iter(inputlist)
for number, letter in zip(it, it):
# ...
This works because zip() gets the next element for each value in the pair from the same iterator, so "30" first, then "M", etc.:
>>> example = ['124', 'M', '19', 'M', '7', 'M']
>>> it = iter(example)
>>> for number, letter in zip(it, it):
... print(number, letter)
...
124 M
19 M
7 M
However, for short lists it is perfectly fine to use slicing, as it can be understood more easily.
Next, you can make the summing a little easier by using the itertools.groupby() function to give you your number + letter pairs as separate groups. That function takes an input sequence, and a function to produce the group identifier. When you then loop over its output you are given that group identifier and an iterator to access the group members (those elements that have the same group value).
Just pass it the zip() iterator build before, and either lambda pair: pair[1] or operator.itemgetter(1); the latter is a little faster but does the same thing as the lambda, get the letter from the number + letter pair.
With separate groups, the logic starts to look a lot simpler:
from itertools import groupby
from operator import itemgetter
def sum_m_values(values):
summed = []
it = iter(values)
paired = zip(it, it)
for letter, grouped in groupby(paired, itemgetter(1)):
if letter == "M":
total = sum(int(number) for number, _ in grouped)
summed += (str(total), letter)
else:
# add the (number, "D") as separate elements
for number, letter in grouped:
summed += (number, letter)
return summed
The output of the function hasn't changed, only the implementation.
Finally, we could turn the function into a generator function, by replacing the summed += ... statements with yield from ..., so it'll still generate a sequence of numeric strings and letters:
from itertools import groupby
from operator import itemgetter
def sum_m_values(values):
it = iter(values)
paired = zip(it, it)
for letter, grouped in groupby(paired, itemgetter(1)):
if letter == "M":
total = sum(int(number) for number, _ in grouped)
yield from (str(total), letter)
else:
# add the (number, "D") as separate elements
for number, letter in grouped:
yield from (number, letter)
You can then use list(sum_m_values(...)) to get a list again, or just use the generator as-is. For long inputs, that could be the preferred option as that means you never need to keep everything in memory all at once.
If you can guarantee that only numbers with M repeat (so a D pair is always followed by an M pair or is the last pair in the sequence), you can even just drop the if test and just always sum:
from itertools import groupby
from operator import itemgetter
def sum_m_values(values):
it = iter(values)
paired = zip(it, it)
for letter, grouped in groupby(paired, itemgetter(1)):
yield str(sum(int(number) for number, _ in grouped))
yield letter
This works because there will only ever be one number value per D group, summing won’t make that into a different number.
A:
solution using itertools package:
>>> from itertools import groupby, chain
>>> records = [
... ['20', 'M', '10', 'M', '1', 'D', '14', 'M', '106', 'M'],
... ['124', 'M', '19', 'M', '7', 'M'],
... ['19', 'M', '131', 'M'],
... ['3', 'M', '19', 'M', '128', 'M'],
... ['12', 'M', '138', 'M'],
... ]
>>> res = []
>>> for rec in records:
... res.append(list(
... chain.from_iterable(
... map(
... lambda x: (
... str(sum(map(lambda y: y[0], x[1]))),
... x[0],
... ),
... groupby(
... zip(map(int, rec[::2]), rec[1::2]),
... lambda k: k[1]
... )
... )
... )
... ))
...
>>> res
[['30', 'M', '1', 'D', '120', 'M'], ['150', 'M'], ['150', 'M'], ['150', 'M'], ['150', 'M']]
A:
Suppose you have that list of lists as input:
LoL=[
['20', 'M', '10', 'M', '1', 'D', '14', 'M', '106', 'M'],
['20', 'M', '10', 'M', '1', 'D', '2', 'D', '14', 'M', '106', 'M'],
['124', 'M', '19', 'M', '7', 'M'],
['19', 'M', '131', 'M'],
['3', 'M', '19', 'M', '128', 'M'],
['12', 'M', '138', 'M'],
]
If you want to sum consecutive values of M (in each sub list) you can use groupby from itertools to step through the list by the second element:
from itertools import groupby
for l in LoL:
result=[]
for k, v in groupby((l[x:x+2] for x in range(0,len(l),2)),
key=lambda l: l[1]):
result.extend([sum(int(l[0]) for l in v), k])
print(result)
Prints:
[30, 'M', 1, 'D', 120, 'M']
[30, 'M', 3, 'D', 120, 'M']
[150, 'M']
[150, 'M']
[150, 'M']
[150, 'M']
If you only want to sum 'M' entries, just test k:
for l in LoL:
result=[]
for k, v in groupby((l[x:x+2] for x in range(0,len(l),2)),
key=lambda l: l[1]):
if k=='M':
result.extend([sum(int(l[0]) for l in v), k])
else:
for e in v:
result.extend([e[0], k])
print(result)
Prints:
[30, 'M', '1', 'D', 120, 'M']
[30, 'M', '1', 'D', '2', 'D', 120, 'M']
[150, 'M']
[150, 'M']
[150, 'M']
[150, 'M']
|
sum elements in python list if match condition
|
I have a variable with lists with varied number of elements:
['20', 'M', '10', 'M', '1', 'D', '14', 'M', '106', 'M']
['124', 'M', '19', 'M', '7', 'M']
['19', 'M', '131', 'M']
['3', 'M', '19', 'M', '128', 'M']
['12', 'M', '138', 'M']
Variable is always number, letter and order matters.
I would to add the values only of consecutive Ms to be (i.e. if there is a D, skip the sum):
['30', 'M', '1', 'D', '120', 'M']
['150', 'M']
['150', 'M']
['150', 'M']
['150', 'M']
ps. the complete story is that I want to convert soft clips to match in a bam file, but got stuck in that step.
#!/usr/bin/python
import sys
import pysam
bamFile = sys.argv[1];
bam = pysam.AlignmentFile(bamFile, 'rb')
for read in bam:
cigar=read.cigarstring
sepa = re.findall('(\d+|[A-Za-z]+)', cigar)
for i in range(len(sepa)):
if sepa[i] == 'S':
sepa[i] = 'M'
|
[
"You can slice Python lists using a step (sometimes called a stride), you can use this to get every second element, starting at index 1 (for the first letter):\n>>> example = ['30', 'M', '1', 'D', '120', 'M']\n>>> example[1::2]\n['M', 'D', 'M']\n\nThe [1::2] syntax means: start at index 1, go on until you run out of elements (nothing entered between the : delimiters), and step over the list to return every second value.\nYou can do the same thing for the numbers, using [::2], so begin with the value right at the start and take every other value.\nIf you then combine this with the zip() function you can pair up your numbers and letters to figure out what to sum:\ndef sum_m_values(values):\n summed = []\n m_sum = 0\n for number, letter in zip(values[::2], values[1::2]):\n if letter != \"M\":\n if m_sum:\n summed += (str(m_sum), \"M\")\n m_sum = 0\n summed += (number, letter)\n else:\n m_sum += int(number)\n if m_sum:\n summed += (str(m_sum), \"M\")\n return summed\n\nThe above function takes your list of numbers and letters and:\n\ncreates a list for the results\ntracks a running sum of \"M\" values\npairs up the numbers and letters\nfor each pair:\n\nif it is a number and \"M\", add that value (as an integer) to the running sum.\notherwise, adds the running sum (if any) to the list with the letter \"M\", then adds the current number and letter too.\n\n\nafter all pairs are processed, adds the running sum and the letter \"M\", if there is any.\n\nThis covers all your example inputs:\n>>> def sum_m_values(values):\n... summed = []\n... m_sum = 0\n... for number, letter in zip(values[::2], values[1::2]):\n... if letter != \"M\":\n... if m_sum:\n... summed += (str(m_sum), \"M\")\n... m_sum = 0\n... summed += (number, letter)\n... else:\n... m_sum += int(number)\n... if m_sum:\n... summed += (str(m_sum), \"M\")\n... return summed\n...\n>>> examples = [\n... ['20', 'M', '10', 'M', '1', 'D', '14', 'M', '106', 'M'],\n... ['124', 'M', '19', 'M', '7', 'M'],\n... ['19', 'M', '131', 'M'],\n... ['3', 'M', '19', 'M', '128', 'M'],\n... ['12', 'M', '138', 'M'],\n... ]\n>>> for example in examples:\n... print(example, \"->\", sum_m_values(example))\n...\n['20', 'M', '10', 'M', '1', 'D', '14', 'M', '106', 'M'] -> ['30', 'M', '1', 'D', '120', 'M']\n['124', 'M', '19', 'M', '7', 'M'] -> ['150', 'M']\n['19', 'M', '131', 'M'] -> ['150', 'M']\n['3', 'M', '19', 'M', '128', 'M'] -> ['150', 'M']\n['12', 'M', '138', 'M'] -> ['150', 'M']\n\nThere are other methods of looping over a list in fixed-sized groups; you can also create an iterator for the list with iter()and then use zip() to pull in consecutive elements into pairs:\nit = iter(inputlist)\nfor number, letter in zip(it, it):\n # ...\n\nThis works because zip() gets the next element for each value in the pair from the same iterator, so \"30\" first, then \"M\", etc.:\n>>> example = ['124', 'M', '19', 'M', '7', 'M']\n>>> it = iter(example)\n>>> for number, letter in zip(it, it):\n... print(number, letter)\n...\n124 M\n19 M\n7 M\n\nHowever, for short lists it is perfectly fine to use slicing, as it can be understood more easily.\nNext, you can make the summing a little easier by using the itertools.groupby() function to give you your number + letter pairs as separate groups. That function takes an input sequence, and a function to produce the group identifier. When you then loop over its output you are given that group identifier and an iterator to access the group members (those elements that have the same group value).\nJust pass it the zip() iterator build before, and either lambda pair: pair[1] or operator.itemgetter(1); the latter is a little faster but does the same thing as the lambda, get the letter from the number + letter pair.\nWith separate groups, the logic starts to look a lot simpler:\nfrom itertools import groupby\nfrom operator import itemgetter\n\ndef sum_m_values(values):\n summed = []\n it = iter(values)\n paired = zip(it, it)\n\n for letter, grouped in groupby(paired, itemgetter(1)):\n if letter == \"M\":\n total = sum(int(number) for number, _ in grouped)\n summed += (str(total), letter)\n else:\n # add the (number, \"D\") as separate elements\n for number, letter in grouped:\n summed += (number, letter)\n \n return summed\n\nThe output of the function hasn't changed, only the implementation.\nFinally, we could turn the function into a generator function, by replacing the summed += ... statements with yield from ..., so it'll still generate a sequence of numeric strings and letters:\nfrom itertools import groupby\nfrom operator import itemgetter\n\ndef sum_m_values(values):\n it = iter(values)\n paired = zip(it, it)\n\n for letter, grouped in groupby(paired, itemgetter(1)):\n if letter == \"M\":\n total = sum(int(number) for number, _ in grouped)\n yield from (str(total), letter)\n else:\n # add the (number, \"D\") as separate elements\n for number, letter in grouped:\n yield from (number, letter)\n\n\nYou can then use list(sum_m_values(...)) to get a list again, or just use the generator as-is. For long inputs, that could be the preferred option as that means you never need to keep everything in memory all at once.\nIf you can guarantee that only numbers with M repeat (so a D pair is always followed by an M pair or is the last pair in the sequence), you can even just drop the if test and just always sum:\nfrom itertools import groupby\nfrom operator import itemgetter\n\ndef sum_m_values(values):\n it = iter(values)\n paired = zip(it, it)\n\n for letter, grouped in groupby(paired, itemgetter(1)):\n yield str(sum(int(number) for number, _ in grouped))\n yield letter\n\nThis works because there will only ever be one number value per D group, summing won’t make that into a different number.\n",
"solution using itertools package:\n>>> from itertools import groupby, chain\n>>> records = [\n... ['20', 'M', '10', 'M', '1', 'D', '14', 'M', '106', 'M'],\n... ['124', 'M', '19', 'M', '7', 'M'],\n... ['19', 'M', '131', 'M'],\n... ['3', 'M', '19', 'M', '128', 'M'],\n... ['12', 'M', '138', 'M'],\n... ]\n>>> res = []\n>>> for rec in records:\n... res.append(list(\n... chain.from_iterable(\n... map(\n... lambda x: (\n... str(sum(map(lambda y: y[0], x[1]))),\n... x[0],\n... ),\n... groupby(\n... zip(map(int, rec[::2]), rec[1::2]),\n... lambda k: k[1]\n... )\n... )\n... )\n... ))\n...\n>>> res\n[['30', 'M', '1', 'D', '120', 'M'], ['150', 'M'], ['150', 'M'], ['150', 'M'], ['150', 'M']]\n\n",
"Suppose you have that list of lists as input:\nLoL=[\n ['20', 'M', '10', 'M', '1', 'D', '14', 'M', '106', 'M'],\n ['20', 'M', '10', 'M', '1', 'D', '2', 'D', '14', 'M', '106', 'M'],\n ['124', 'M', '19', 'M', '7', 'M'],\n ['19', 'M', '131', 'M'],\n ['3', 'M', '19', 'M', '128', 'M'],\n ['12', 'M', '138', 'M'],\n]\n\nIf you want to sum consecutive values of M (in each sub list) you can use groupby from itertools to step through the list by the second element:\nfrom itertools import groupby\n\n\nfor l in LoL:\n result=[]\n for k, v in groupby((l[x:x+2] for x in range(0,len(l),2)), \n key=lambda l: l[1]):\n result.extend([sum(int(l[0]) for l in v), k])\n print(result)\n\nPrints:\n[30, 'M', 1, 'D', 120, 'M']\n[30, 'M', 3, 'D', 120, 'M']\n[150, 'M']\n[150, 'M']\n[150, 'M']\n[150, 'M']\n\nIf you only want to sum 'M' entries, just test k:\nfor l in LoL:\n result=[]\n for k, v in groupby((l[x:x+2] for x in range(0,len(l),2)), \n key=lambda l: l[1]):\n if k=='M':\n result.extend([sum(int(l[0]) for l in v), k])\n else:\n for e in v:\n result.extend([e[0], k])\n print(result)\n\nPrints:\n[30, 'M', '1', 'D', 120, 'M']\n[30, 'M', '1', 'D', '2', 'D', 120, 'M']\n[150, 'M']\n[150, 'M']\n[150, 'M']\n[150, 'M']\n\n"
] |
[
3,
0,
0
] |
[] |
[] |
[
"bam",
"pysam",
"python"
] |
stackoverflow_0074583505_bam_pysam_python.txt
|
Q:
Add position to a NetworkX graph using dictionary
I have a DiGraph object called G1, a graph network with edges. G1 is composed by a list of nodes and I want to give them coordinates stored in a python dictionary.
This is the list of nodes:
LIST OF NODES
For every node I have built a python dictionary with node's name as keys and a tuple of coordinates as values:
DICTIONARY WITH COORDINATES
I want to add the attribute position (pos) to every node with those coordinates.
At the moment I have tried using this cycle:
FOR LOOP TO ADD COORDINATES
But as a result only the last node appears to have coordinates, it seems like the data are being subscribed with this method:
ERROR
The result should be a graph network plotted on a xy space with the right coordinates obtained with the code:
PLOT THE GRAPH
I am obtaining the following error:
KeyError: (78.44, 88.3)
A:
I think it's mostly syntax errors here. Try this:
for node, pos in avg.items():
G1.nodes[node]['pos'] = pos
Then, when building your visual, build your list of positions beforehand like this and just use the pos=pos convention when calling nx.draw().
pos = {node: G.nodes[node]['pos'] for node in G.nodes()}
**** EDIT: ****
There's a built-in way to do this that is much cleaner:
nx.set_node_attributes(G1, avg, 'pos')
Then, when drawing, use:
nx.draw(G1, pos=nx.get_nodes_attributes(G1, 'pos'))
|
Add position to a NetworkX graph using dictionary
|
I have a DiGraph object called G1, a graph network with edges. G1 is composed by a list of nodes and I want to give them coordinates stored in a python dictionary.
This is the list of nodes:
LIST OF NODES
For every node I have built a python dictionary with node's name as keys and a tuple of coordinates as values:
DICTIONARY WITH COORDINATES
I want to add the attribute position (pos) to every node with those coordinates.
At the moment I have tried using this cycle:
FOR LOOP TO ADD COORDINATES
But as a result only the last node appears to have coordinates, it seems like the data are being subscribed with this method:
ERROR
The result should be a graph network plotted on a xy space with the right coordinates obtained with the code:
PLOT THE GRAPH
I am obtaining the following error:
KeyError: (78.44, 88.3)
|
[
"I think it's mostly syntax errors here. Try this:\nfor node, pos in avg.items():\n G1.nodes[node]['pos'] = pos\n\nThen, when building your visual, build your list of positions beforehand like this and just use the pos=pos convention when calling nx.draw().\npos = {node: G.nodes[node]['pos'] for node in G.nodes()}\n\n\n**** EDIT: ****\nThere's a built-in way to do this that is much cleaner:\nnx.set_node_attributes(G1, avg, 'pos')\n\nThen, when drawing, use:\nnx.draw(G1, pos=nx.get_nodes_attributes(G1, 'pos'))\n\n"
] |
[
0
] |
[] |
[] |
[
"coordinates",
"dictionary",
"networkx",
"python"
] |
stackoverflow_0074581466_coordinates_dictionary_networkx_python.txt
|
Q:
what does .models mean in Django?
I am trying to import a class named 'Questions' from my models.py to admin.py
from .models import Questions
I don't understand why we have to use a period in '.models', what does it mean and what exactly is it pin pointing to?
I tried this combinations but it was no avail
from models import Questions
from Model.models import Questions
A:
This is due to relative import. you see their are 2 types of import statement:
Absolute import: they start from the root of the project. Like in Django where the manage.py is, that is the root. So your import statement can be written as
from {AppName}.models import Questions
But here you are using relative path. Relative because you start from the current directory you are in and not the root. So in .models the . actually means current directory. You can not use models because there is no models in root directory.
For more in depth detail try this Python imports
A:
That's a relative import. It means go back one level in the folder tree and import models.
This:
from .models import Questions
is the same as this:
from my_folder_containing_models.models import Questions
|
what does .models mean in Django?
|
I am trying to import a class named 'Questions' from my models.py to admin.py
from .models import Questions
I don't understand why we have to use a period in '.models', what does it mean and what exactly is it pin pointing to?
I tried this combinations but it was no avail
from models import Questions
from Model.models import Questions
|
[
"This is due to relative import. you see their are 2 types of import statement:\n\nAbsolute import: they start from the root of the project. Like in Django where the manage.py is, that is the root. So your import statement can be written as\nfrom {AppName}.models import Questions\n\nBut here you are using relative path. Relative because you start from the current directory you are in and not the root. So in .models the . actually means current directory. You can not use models because there is no models in root directory.\n\n\nFor more in depth detail try this Python imports\n",
"That's a relative import. It means go back one level in the folder tree and import models.\nThis:\nfrom .models import Questions\n\nis the same as this:\nfrom my_folder_containing_models.models import Questions\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"django",
"python",
"python_import"
] |
stackoverflow_0074583711_django_python_python_import.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.