when i take input from user and wanna convert that input,the system errors - python-2.x

[enter image description here][1]
from word2number import w2n
w2n.word_to_num('one')
1
q = input('write your number letters : ')
>>>two
w2n.word_to_num('q')
>>>NameError: name 'two' is not defined
i use word2number package to convert word to number, like; two = 2. when i take input from user and wanna convert that input,the system errors.

Please post the full code as text that you are trying that is giving you errors.
But the code from the Word2number documentation is working fine for me.
https://pypi.org/project/word2number/
Python 3
from word2number import w2n
print(w2n.word_to_num('point one'))
Output:
0.1
Python 2
from word2number import w2n
print w2n.word_to_num('point one')
Output:
0.1

Related

Python TTk simple if statement

I am new to Python, How can I can display the message "The water level is too high" only when the value of the first slide is above 80.00 ?
This is my try:
if value_label>80:
current_value_label99 = ttk.Label(
root,style="Red.TCheckbutton",
text='Water Level Too High!'
)
current_value_label99.grid(
row=7,
columnspan=2,
sticky='n',
ipadx=20,
ipady=20
)
enter image description here
Full code: https://jpst.it/31nkd

Combine/Merge every x images together with title of each pict (linux)

I have some folders containing many jpg pictures (number depends on the folder)
I would like for instance to combine every 4 pict** together with the title of the image (see pict below).
(In case there is not exactly 4 image on the last sequence, I should get the number of left picture such as 3 2 or 1)
**Ideally I could change that number to other numbers like 5 6 10 (the number I chose would depend on the context) and I could chose the number of columns (I showed 2 column in my example below)
How can i perform this on Linux command or any Linux free/open-source software?
As I did not find what I want I created my own python code to solve this (it's probably not the most perfects script of the century but it works)
"""
Prints a collage according to desired number of column and rows with title of file
Instruction
1. Put all jpg picture in same folder [tested sucessfully on 12mb per pict]
2. select desired columns in NO_COL
3. select desired rowsin in NO_ROW
4. run the script which will output the collage with <cur_date>_export.png files
"""
#import libraries
import time
import os
import imageio as iio
from matplotlib import pyplot as plt
def render_collage(pict_file_name_list):
""" create one collage """
fig = plt.figure(figsize=(40, 28)) #change if needed
cnt = 1
for cur_img_name in pict_file_name_list:
img_var = iio.imread(cur_img_name)
fig.add_subplot(NO_COL, NO_ROW, cnt)
plt.imshow(img_var)
plt.axis('off')
plt.title(cur_img_name, fontsize = 30) #change if needed
cnt = cnt + 1
cur_date = time.strftime("%Y-%m-%d--%H-%M-%s")
fig.savefig(cur_date+'_export.png')
NO_COL = 3
NO_ROW = 3
NBR_IMG_COLLAGE = NO_COL * NO_ROW
img_list_name = [elem for elem in os.listdir() if 'jpg' in elem] #keep only file having .jpg
while len(img_list_name) >= 1:
sub_list = img_list_name[:NBR_IMG_COLLAGE]
render_collage(sub_list)
del img_list_name[:NBR_IMG_COLLAGE]

How to retrieve and format wifi MAC address in MicroPython on ESP32?

I have the following MicroPython code running on an ESP32:
import network
wlan_sta = network.WLAN(network.STA_IF)
wlan_sta.active(True)
wlan_mac = wlan_sta.config('mac')
print("MAC Address:", wlan_mac) # Show MAC for peering
The output looks like this:
MAC Address: b'0\xae\xa4z\xa7$'
I would like to display it in the more familiar format of six pairs of hex digits, like this:
MAC Address: AABBCC112233
After searching for a solution on the internet, I've tried:
print("MAC Address:", str(wlan_mac)) but it displays the same as when not using str()
print("MAC Address:", hex(wlan_mac)) but it results in TypeError: can't convert bytes to int
print("MAC Address:", wlan_mac.hex()) but it says AttributeError: 'bytes' object has no attribute 'hex'
I am also a little suspicious of the bytes retrieved from wlan_sta.config('mac'). I would have expected something that looked more like b'\xaa\xbb\xcc\x11\x22\x33' instead of b'0\xae\xa4z\xa7$'. The z and the $ seem very out of place for something that should be hexadecimal and it seems too short for what should be six pairs of digits.
So my question is two-fold:
Am I using the correct method to get the MAC address?
If it is correct, how can I format it as six pairs of hex digits?
I am also a little suspicious of the bytes retrieved from wlan_sta.config('mac'). I would have expected something that looked more like b'\xaa\xbb\xcc\x11\x22\x33' instead of b'0\xae\xa4z\xa7$'. The z and the $ seem very out of place for something that should be hexadecimal and it seems too short for what should be six pairs of digits.
You're not getting back a hexadecimal string, you're getting a byte string. So if the MAC address contains the value 7A, then the byte string will contain z (which has ASCII value 122 (hex 7A)).
Am I using the correct method to get the MAC address?
You are!
If it is correct, how can I format it as six pairs of hex digits?
If you want to print the MAC address as a hex string, you can use the
ubinascii.hexlify method:
>>> import ubinascii
>>> import network
>>> wlan_sta = network.WLAN(network.STA_IF)
>>> wlan_sta.active(True)
>>> wlan_mac = wlan_sta.config('mac')
>>> print(ubinascii.hexlify(wlan_mac).decode())
30aea47aa724
Or maybe:
>>> print(ubinascii.hexlify(wlan_mac).decode().upper())
30AEA47AA724
You can use:
def wifi_connect(ssid, pwd):
sta_if = None
import network
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print("connecting to network...")
sta_if.active(True)
sta_if.connect(ssid, pwd)
while not sta_if.isconnected():
pass
print("----------------------------------------")
print("network config:", sta_if.ifconfig())
print("----------------------------------------")
get_my_mac_addr(sta_if)
Then:
def get_my_mac_addr(sta_if):
import ubinascii
import network
wlan_mac = sta_if.config('mac')
my_mac_addr = ubinascii.hexlify(wlan_mac).decode()
my_mac_addr = format_mac_addr(my_mac_addr)
Then:
def format_mac_addr(addr):
mac_addr = addr
mac_addr = mac_addr.upper()
new_mac = ""
for i in range(0, len(mac_addr),2):
#print(mac_addr[i] + mac_addr[i+1])
if (i == len(mac_addr) - 2):
new_mac = new_mac + mac_addr[i] + mac_addr[i+1]
else:
new_mac = new_mac + mac_addr[i] + mac_addr[i+1] + ":"
print("----------------------------------------")
print("My MAC Address:" + new_mac)
print("----------------------------------------")
return new_mac
Return:
----------------------------------------
My MAC Address:xx:xx:xx:xx:xx:xx
----------------------------------------

How to get the correlation matrix of a pyspark data frame? NEW 2020

I have the same question from this topic:
How to get the correlation matrix of a pyspark data frame?
"I have a big pyspark data frame. I want to get its correlation matrix. I know how to get it with a pandas data frame.But my data is too big to convert to pandas. So I need to get the result with pyspark data frame.I searched other similar questions, the answers don't work for me. Can any body help me? Thanks!"
df4 is my dataset, he has 9 columns and all of them are integers:
reference__YM_unix:integer
tenure_band:integer
cei_global_band:integer
x_band:integer
y_band:integer
limit_band:integer
spend_band:integer
transactions_band:integer
spend_total:integer
I have first done this step:
# convert to vector column first
vector_col = "corr_features"
assembler = VectorAssembler(inputCols=df4.columns, outputCol=vector_col)
df_vector = assembler.transform(df4).select(vector_col)
# get correlation matrix
matrix = Correlation.corr(df_vector, vector_col)
And got the following output:
(matrix.collect()[0]["pearson({})".format(vector_col)].values)
Out[33]: array([ 1. , 0.0760092 , 0.09051543, 0.07550633, -0.08058203,
-0.24106848, 0.08229602, -0.02975856, -0.03108094, 0.0760092 ,
1. , 0.14792512, -0.10744735, 0.29481762, -0.04490072,
-0.27454922, 0.23242408, 0.32051685, 0.09051543, 0.14792512,
1. , -0.03708623, 0.13719527, -0.01135489, 0.08706559,
0.24713638, 0.37453265, 0.07550633, -0.10744735, -0.03708623,
1. , -0.49640664, 0.01885793, 0.25877516, -0.05019079,
-0.13878844, -0.08058203, 0.29481762, 0.13719527, -0.49640664,
1. , 0.01080777, -0.42319841, 0.01229877, 0.16440178,
-0.24106848, -0.04490072, -0.01135489, 0.01885793, 0.01080777,
1. , 0.00523737, 0.01244241, 0.01811365, 0.08229602,
-0.27454922, 0.08706559, 0.25877516, -0.42319841, 0.00523737,
1. , 0.32888075, 0.21416322, -0.02975856, 0.23242408,
0.24713638, -0.05019079, 0.01229877, 0.01244241, 0.32888075,
1. , 0.53310864, -0.03108094, 0.32051685, 0.37453265,
-0.13878844, 0.16440178, 0.01811365, 0.21416322, 0.53310864,
1. ])
I've tried to insert this result on arrays or an excel file but it didnt work.
I did:
matrix2 = (matrix.collect()[0]["pearson({})".format(vector_col)])
Then I got the following error when I tried to display this info:
display(matrix2)
Exception: ML model display does not yet support model type <class 'pyspark.ml.linalg.DenseMatrix'>.
I was expecting to insert the name of the columns back from df4 but it didnt succeed, I've read that I need to use df4.columns but I have no idea how does it works.
Finally, I was expecting to print the following graph that I've seen from medium article
https://medium.com/towards-artificial-intelligence/feature-selection-and-dimensionality-reduction-using-covariance-matrix-plot-b4c7498abd07
But also it didn't work:
from sklearn.preprocessing import StandardScaler
stdsc = StandardScaler()
X_std = stdsc.fit_transform(df4.iloc[:,range(0,7)].values)
cov_mat =np.cov(X_std.T)
plt.figure(figsize=(10,10))
sns.set(font_scale=1.5)
hm = sns.heatmap(cov_mat,
cbar=True,
annot=True,
square=True,
fmt='.2f',
annot_kws={'size': 12},
cmap='coolwarm',
yticklabels=cols,
xticklabels=cols)
plt.title('Covariance matrix showing correlation coefficients', size = 18)
plt.tight_layout()
plt.show()
AttributeError: 'DataFrame' object has no attribute 'iloc'
I've tried to replace df4 to matrix2 and didn't work too
You can use the following to get the correlation matrix in a form you can manipulate:
matrix = matrix.toArray().tolist()
From there you can convert to a dataframe pd.DataFrame(matrix) which would allow you to plot the heatmap, or save to excel etc.

Cls for fields generated with synalm disagree with input Cls and Cls for fields generated using synfast

I am generating random healpix maps from an input angular power spectrum Cl. If I use healpy.synalm, then healpy.alm2map, and finally test the map by running healpy.anafast on the generated map, the output and input power spectra do not agree, especially at high l, the output power spectrum is above the input (See plot produced by code below). If I directly use healpy.synfast, I get an output power spectrum that agrees with the input. The same applies if I use the alms from healpy.synfast and generate a map from the synfast alms using healpy.alm2map. When I look into the source code of synfast, it seems to just call synalm and alm2map, so I don't understand, why their results disagree. My test code looks like this:
import numpy as np
import matplotlib.pyplot as plt
import classy
import healpy as hp
NSIDE = 32
A_s=2.3e-9
n_s=0.9624
h=0.6711
omega_b=0.022068
omega_cdm=0.12029
params = {
'output': 'dCl, mPk',
'A_s': A_s,
'n_s': n_s,
'h': h,
'omega_b': omega_b,
'omega_cdm': omega_cdm,
'selection_mean': '0.55',
'selection_magnification_bias_analytic': 'yes',
'selection_bias_analytic': 'yes',
'selection_dNdz_evolution_analytic': 'yes'}
cosmo = classy.Class()
cosmo.set(params)
cosmo.compute()
theory_cl=cosmo.density_cl()['dd']
data_map,data_alm=hp.synfast(theory_cl[0],NSIDE,alm=True)
data_cl=hp.anafast(data_map)
plt.plot(np.arange(len(data_cl)),data_cl,label="synfast")
data_map=hp.alm2map(data_alm,NSIDE)
data_cl=hp.anafast(data_map)
plt.plot(np.arange(len(data_cl)),data_cl,label="synfast using alm")
data_alm=hp.synalm(theory_cl[0])
data_map=hp.alm2map(data_alm,NSIDE)
data_cl=hp.anafast(data_map)
plt.plot(np.arange(len(data_cl)),data_cl,label="synalm")
plt.plot(np.arange(min(len(data_cl),len(theory_cl[0]))),theory_cl[0][:len(data_cl)],label="Theory")
plt.xlabel(r'$\ell$')
plt.ylabel(r'$C_\ell$')
plt.legend()
plt.show()
The offset becomes larger for lower NSIDE.
Thank you very much for your help.
Sorry, I missed that synfast knows about NSIDE, so the lmax is by default based on NSIDE, whereas synalm does not know about it, so it takes the maximum l of the input spectrum as lmax. Setting lmax to 3 * NSIDE -1 in synalm resolves the discrepancy.

Resources