Convert Oracle RAW of NUMBER to .NET Int64 - arrays

I have converted this number 735969 to oracle raw this this funcion:
UTL_RAW.CAST_FROM_NUMBER(735969)
and saved to database.
Then I get saved data from .NET application into byte[] variable bytesFromDB.
Content got into variable is
byte[4] { 195, 64, 70, 60 }
If I try to convert it int with this function:
BitConverter.ToInt32(bytesFromDB, 0)
It returns a differente number (1178356419) infact if I convert 735969 into array with .NET function
BitConverter.GetBytes(735969)
I get a different byte array:
byte[4] { 225, 58, 11, 0 }
This is the .Net FIDDLE
This is the Oracle FIDDLE
Why this???
Which is BAD? ORACLE or .NET??

Related

struct unpack error when converting datetime(2) datatype in SQL Server to string

def datetime_as_string(raw_bytes):
#
tup = struct.unpack('8h', raw_bytes)
print(tup)
return datetime.datetime(tup[0], tup[1], tup[2], tup[3], tup[4], tup[5], 0).strftime('%Y-%m-%d %H:%M:%S.%f')
I am writing this function to unpack datetime.datetime(2022, 11, 18, 13, 42, 31, 316666) with data type datetime2(7) in SQL Server to convert it to a string but I am unable to do this as it unpacks to (2022, 11, 18, 13, 42, 31, -3252, 4831) whereas I was expecting it to unpack it to (2022, 11, 18, 13, 42, 31, 316666).
I am unable to figure out how to if condition to check between datetime2(7) and datetime. When I don't use the output converter in pyodbc the query returned is like this
('103345', datetime.datetime(2022, 6, 9, 13, 51, 42, 856667), datetime.datetime(2022, 6, 9, 13, 51, 42, 856667), '2022-06-09', 'ENTRY', 'ENTRY')
and I want it to be something like this
('103345', '2022-06-09 13:51:42.856667', '2022-06-09 13:51:42.856667', '2022-06-09', 'ENTRY', 'ENTRY')
Kindly help me figure where I might be doing wrong.
The other part of my script which is working correctly and converting date datatype to string when I comment the above function.
def convert_date_to_string(raw_bytes):
tup = struct.unpack('3h', raw_bytes)
# print(tup)
return datetime.date(tup[0], tup[1], tup[2]).strftime('%Y-%m-%d')
# check if the connection is successful
def test_query():
try:
conn = po.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
# add converter for datetime and date
conn.add_output_converter(po.SQL_TYPE_TIMESTAMP, datetime_as_string)
conn.add_output_converter(po.SQL_TYPE_DATE, convert_date_to_string)
print("Connection Successful")
except Exception as e:
print("Connection Failed")
print(e)
Tldr; I am trying to get output of sql query in pyodc as string rather than datetime.datetime() object for which I wrote a output converter function and I get this error
struct unpack error 8 bytes buffer required
or
unpacking incorrectly

save array of object in file in python

I want to save array of my object in file in python and I test pickle, numpy,..but it doesn't work.
my class that I want to save instance of it in file is:
class pesrson():
def __init__(self,name,centralwidget):
self.name=name
self.centralwidget=centralwidget
def config(self):
self.frame_eployee = QFrame(self.centralwidget)
self.frame_eployee.setObjectName(u"frame_eployee")
self.frame_eployee.setGeometry(QRect(20, 590, 321, 51))
self.frame_eployee.setStyleSheet(u"color:rgb(85, 170, 255)")
self.frame_eployee.setFrameShape(QFrame.StyledPanel)
self.frame_eployee.setFrameShadow(QFrame.Raised)
self.label_fix_logo_user = QLabel(self.frame_eployee)
self.label_fix_logo_user.setObjectName(u"label_fix_logo_user")
self.label_fix_logo_user.setGeometry(QRect(10, 0, 41, 41))
self.label_fix_logo_user.setPixmap(QPixmap(u"D:/V2.0.0/Programme/qt/UI design/picture/user.svg"))
self.label_name_employee = QLabel(self.frame_eployee)
self.label_name_employee.setObjectName(u"label_name_employee")
self.label_name_employee.setGeometry(QRect(60, 10, 101, 21))
self.label_name_employee.setStyleSheet(u"color: rgb(255, 255, 255);\n"
"font: 25 10pt \"Segoe UI Light\";")
self.label_tim_login = QLabel(self.frame_eployee)
self.label_tim_login.setObjectName(u"label_tim_login")
self.label_tim_login.setGeometry(QRect(190, 10, 61, 21))
self.label_tim_login.setStyleSheet(u"color: rgb(255, 255, 255);\n"
"font: 25 10pt \"Segoe UI Light\";")
self.label_time_logOut = QLabel(self.frame_eployee)
self.label_time_logOut.setObjectName(u"label_time_logOut")
self.label_time_logOut.setGeometry(QRect(250, 10, 61, 21))
self.label_time_logOut.setStyleSheet(u"color: rgb(255, 255, 255);\n"
"font: 25 10pt \"Segoe UI Light\";")
self.label_name_employee.setText(QCoreApplication.translate("MainWindow", self.name, None))
self.label_tim_login.setText(
QCoreApplication.translate("MainWindow", u"<html><head/><body><p align=\"center\">08:34</p></body></html>",
None))
self.label_time_logOut.setText(
QCoreApplication.translate("MainWindow", u"<html><head/><body><p align=\"center\">08:34</p></body></html>",
None))
return self.frame_eployee
I create this object with this code:
p=pesrson("faezeh",self.ui.centralwidget)
self.ui.verticalLayout.addWidget(p.config())
self.tree.append(p)
now I want to save this array then read them and can use all attributes.
this error is when I use json :
TypeError: Object of type person is not JSON serializable
<employee.pesrson object at 0x000001DD17C7B7F0>
this error when I use pickle:
Possibly unsupported): cannot pickle 'PySide2.QtWidgets.QFrame' object
you could use the pickle module in the standard library and also you could use a database instead of a file. I think it would fit your problem.

How to have the xlim with seaborn automatically adjust based on dataframe date range

I am trying to loop through plots. Each "station" is a pandas dataframe has a single water year of data (oct 1 to Spet 29). The data is being read in with this code:
sh_784_2020 = pd.read_csv("sh_784_WY2020.csv", parse_dates=['Date'])
sh_784_2020.columns = ["Index", "Date", "Temp_C","Precip_mm","SnowDepth_cm","SWE_mm","SM2","SM8","SM20"]
My plots loop through but the x-axis always starts at the year 2000 through the current date displayed but my data is from 2006-2020. Is there a way to have the xlim adjust automatically for the date range in the data frame? Or is there a way to create this plot in matyplotlib and not seaborn?
for station in stations:
station['Density'] = station['SWE_mm']/(station['SnowDepth_cm']*10)*100
station['Density range'] = pd.cut( station['Density'], [-np.inf, 25, 30, 35, 40, np.inf])
Date = station.loc[:, 'Date'].values
SWE_mm = station.loc[:, 'SWE_mm'].values
Density = station.loc[:, 'Density'].values
sns.scatterplot(station['Date'], station['SWE_mm'], hue='Density range', data= station, edgecolor = 'none', palette=['grey', 'green', 'gold', 'orange', 'crimson'], alpha= 1)
plt.xlim ()
plt.show()
Plot example 1
Plot example 2
If you upgrade to seaborn 0.11 you should find that the default autoscaling works better, but you can get a good result without upgrading by creating the Axes object before plotting and setting the units, e.g. something like
ax = plt.figure().subplots()
ax.xaxis.update_units(station["Date"])

Python Json Post to Server - bit9

i am trying to create a variable in a python dictionary and post this variable to the a server in a json format to a server.
the server isn't accepting a dict containing a list.
this is the code:
b9RuleData = {'hash': 'fea66a01c8091683539597d529557b8f2f21270e', 'fileState': 3, 'policyIds' : '11' }
b9RuleData2 = {'hash':'ff9586097b762b7d534cad008fc5f0382b5dcff8', 'fileState': 3, 'policyIds' : '12'}
b9RuleData3 = {'hash':'fea66a01c8091683539597d529557b8f2f21270e', 'fileState': 3, 'policyIds' : '13'}
So, what's the best way to write this ? Let's assume that,I have 100 file hashes. I can't keep adding each individual file hash..

ValueError: could not convert string to float: E-3 [duplicate]

This question already has answers here:
Issue querying from Access database: "could not convert string to float: E+6"
(3 answers)
Closed 7 years ago.
I am trying to access some of the columns in a Microsoft Access database table which contains numbers of type double but I am getting the error mentioned in the title.The code used for querying the database is as below, the error is occurring in the line where cur.execute(....) command is executed. Basically I am trying filter out data captured in a particular time interval. If I exclude the columns CM3_Up, CG3_Up, CM3_Down, CG3_Down which contains double data type in the cur.execute(....) command I wont get the error. Same logic was used to access double data type from other tables and it worked fine, I am not sure what is going wrong.
Code:
start =datetime.datetime(2015,03,28,00,00)
a=start
b=start+datetime.timedelta(0,240)
r=7
while a < (start+datetime.timedelta(1)):
params = (a,b)
sql = "SELECT Date_Time, CM3_Up, CG3_Up, CM3_Down, CG3_Down FROM
Lysimeter_Facility_Data_5 WHERE Date_Time >= ? AND Date_Time <= ?"
for row in cur.execute(sql,params):
if row is None:
continue
r = r+1
ws.cell(row = r,column=12).value = row.get('CM3_Up')
ws.cell(row = r,column=13).value = row.get('CG3_Up')
ws.cell(row = r,column=14).value = row.get('CM3_Down')
ws.cell(row = r,column=15).value = row.get('CG3_Down')
a = a+five_min
b = b+five_min
wb.save('..\SE_SW_Lysimeters_Weather_Mass_Experiment-02_03_26_2015.xlsx')
Complete error report:
Traceback (most recent call last):
File "C:\DB_PY\access_mdb\db_to_xl.py", line 318, in <module>
for row in cur.execute(sql,params):
File "build\bdist.win32\egg\pypyodbc.py", line 1920, in next
row = self.fetchone()
File "build\bdist.win32\egg\pypyodbc.py", line 1871, in fetchone
value_list.append(buf_cvt_func(alloc_buffer.value))
ValueError: could not convert string to float: E-3
As to this discussion:
Python: trouble reading number format
the trouble could be that e should be d, like:
float(row.get('CM3_Up').replace('E', 'D'))
Sounds weird to me though, but I know only little of Python.
It sounds like you receive strings like '2.34E-3', so try with a conversion. Don't know Python, but in C# it could be like:
ws.cell(row = r,column=12).value = Convert.ToDouble(row.get('CM3_Up'))
ws.cell(row = r,column=13).value = Convert.ToDouble(row.get('CG3_Up'))
ws.cell(row = r,column=14).value = Convert.ToDouble(row.get('CM3_Down'))
ws.cell(row = r,column=15).value = Convert.ToDouble(row.get('CG3_Down'))

Resources