Passing SAFEARRAY value to COM client - python-3.x

I am trying to Automate a Tool via win32com.client module which expects the Input to be in the following format,The format shown below if specific to MATLAB.
HRESULT StaticStokesParameters([in] SAFEARRAY(double) newVal)
I have no clue what does SAFEARRAY type represent. I have tried to create an 2D array in python, but i keep receiving the following error,
pywintypes.com_error: (-2147352571, 'Type mismatch.', None, 1)
I can read the values out without any problem, but when i assign the same value back as SET argument, then it fails to do so,
EngineMgr = win32com.client.Dispatch("EngineMgr")
Engine = EngineMgr.OpenEngine(0)
d_array = Engine.StaticStokesParameters
print(d_array)
**(-1.0, 0.0, 0.0) # Output of Print Statement**
Engine.StaticStokesParameters = d_array
**Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
Engine.StaticStokesParameters = d_array
File "C:\Users\ashes\Anaconda3\lib\site-packages\win32com\client\dynamic.py", line 549, in __setattr__
self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
pywintypes.com_error: (-2147352571, 'Type mismatch.', None, 1)**

Got this working by importing below shown modules,
from win32com.client import VARIANT
import pythoncom
sop= Engine.StaticStokesParameters
Engine.StaticStokesParameters = VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_R8,sop)

Related

Reading a CSV file with graphviz

The current project I have to do involves reading data from a CSV file and using graphviz to show a visual representation of the data. this is what the code looks like:
import graphviz
import pandas
import os
import math
def save_graph_as_jpg(graph, filename):
graph.save('temp.dot')
src = graphviz.Source.from_file('temp.dot')
src.render(filename, format="jpg")
os.remove(filename)
os.remove('temp.dot')
class Node:
def __init__(self, data, left = None, right = None):
self.left = left
self.right = right
self.data = data
df = pandas.read_csv('decisiontree.csv', index_col = "ID") # df is "data frame"
print(df.to_string())
print(df.info)
nodes = []
nodeMap = {None:None}
for index, row in df[::-1].iterrows():
row = df.index(int[index])
if isinstance(df.loc[row][3], float) and math.isnan(df.loc[row][3]):
df.loc[row][3] = None
if isinstance(df.loc[row][2], float) and math.isnan(df.loc[row][2]):
df.loc[row][2] = None
nodeMap[df.loc[row][0]] = Node(df.loc[row][1],nodeMap[df.loc[row][3]], nodeMap[df.loc[row][2]]), nodes.insert(0,df.loc[row][0])
graph = graphviz.Digraph('structs', filename='structs.gv', node_attr={'shape': 'plaintext', 'ordering':'out'})
for nodeID in nodes:
node = nodeMap[nodeID]
if node.left:
graph.edge(node.data, node.left.data)
if node.right:
graph.edge(node.data, node.right.data)
save_graph_as_jpg(graph, "Decisiontree")
When I run it using IDLE, it returns most of the code just fine, but it gets hung up on line 27:
row = df.index(int[index])
I get a traceback message saying the following:
Traceback (most recent call last):
File "C:\Users...... line 27, in <module>
row = df.index[index]
File "C:\Users......Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pandas\core\indexes\base.py", line 5382, in __getitem__
result = getitem(key)
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
I changed it to:
row = df.index(int[index])
and now I get this as a traceback and index error:
Traceback (most recent call last):
File "C:\Users.......CTML AI\Week 3\Lab3.py", line 27, in <module>
row = df.index(int[index])
TypeError: 'type' object is not subscriptable
You are receiving that error because you tried to use square brackets with the int type, which would try to subscript int as if it were an array. That doesn't work because int is a type that can't be subscripted.[1][2] You probably want to use parentheses instead to cast the type of the index variable to integer. Try changing line 27 to
df.index(int(index))
However, it would work if you had an array named int, but naming your variables the same as builtin types or functions is probably not a good idea.
As of Python 3.9, some types can be subscripted in type hints, e.g. list[int].

How can I remove Attribute error from my Csv program showing? [duplicate]

So I copied and pasted a demo program from the book I am using to learn Python:
#!/usr/bin/env python
import csv
total = 0
priciest = ('',0,0,0)
r = csv.reader(open('purchases.csv'))
for row in r:
cost = float(row[1]) * float(row[2])
total += cost
if cost == priciest[3]:
priciest = row + [cost]
print("You spent", total)
print("Your priciest purchase was", priciest[1], priciest[0], "at a total cost of", priciest[3])
And I get the Error:
Traceback (most recent call last):
File "purchases.py", line 2, in <module>
import csv
File "/Users/Solomon/Desktop/Python/csv.py", line 5, in <module>
r = csv.read(open('purchases.csv'))
AttributeError: 'module' object has no attribute 'read'
Why is this happening? How do I fix it?
Update:
Fixed All The Errors
Now I'm getting:
Traceback (most recent call last):
File "purchases.py", line 6, in <module>
for row in r:
_csv.Error: line contains NULL byte
What was happening in terms of the CSV.py:
I had a file with the same code named csv.py, saved in the same directory. I thought that the fact that it was named csv .py was screwing it up, so I started a new file called purchases.py, but forgot to delete csv
Don't name your file csv.py.
When you do, Python will look in your file for the csv code instead of the standard library csv module.
Edit: to include the important note in the comment: if there's a csv.pyc file left over in that directory, you'll have to delete that. that is Python bytecode which would be used in place of re-running your csv.py file.
There is a discrepancy between the code in the traceback of your error:
r = csv.read(open('purchases.csv'))
And the code you posted:
r = csv.reader(open('purchases.csv'))
So which are you using?
At any rate, fix that indentation error in line 2:
#!/usr/bin/env python
import csv
total = 0
And create your csv reader object with a context handler, so as not to leave the file handle open:
with open('purchases.csv') as f:
r = csv.reader(f)

What does "TypeError: 'NoneType' object is not subscriptable" mean?

I am writing a snake game using Pygame in Python3. However, I keep getting this TypeError, not only do I have no idea what it means I have no idea how to fix it
I haven't really attempted anything as I have no idea what it is or how to fix it. This is the code:
def draw(self, surface, eyes=False):
dis = self.w // self.rows
i = self.pos[0]
j = self.pos[1]
The error message I keep getting is:
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "snake.py", line 179, in <module>
main()
File "snake.py", line 175, in main
redrawWindow(win)
File "snake.py", line 127, in redrawWindow
snack.draw(surface)
File "snake.py", line 25, in draw
i = self.pos[0]
TypeError: 'NoneType' object is not subscriptable
This occurs when you try to index through a Nonetype object, e.g.,
>>> x = None
>>> x[0]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
x[0]
TypeError: 'NoneType' object is not subscriptable
To properly solve your problem, please post the full code or where you set the initial value of self.pos. It seems that you're setting this variable to None.
This appears to be an excerpt from the python tutorial by Tech With Tim: https://techwithtim.net/tutorials/game-development-with-python/snake-pygame/tutorial-1/
It is actually caused by a misplaced return inside of the randomSnack while loop.
Full code here: https://pastebin.com/embed_js/jB6k06hG
If the return is inside the while loop (at line 162 in the pastebin) you get this error. I was following the same tutorial and got this error too.
# When you call (line 145)
snack.draw(surface)
# you are referencing the snack that was created with (line 193)
snack = cube(randomSnack(rows, s), color=(0,255,0))
# The randomSnack function returns an x and y (line 162)
return (x,y)
# that gets passed into the cube object's "start" parameter (line 12)
def __init__(self,start,dirnx=1,dirny=0,color=(255,0,0)):

Procedure on adding image pixel data in a file in newline?

import cv2
import numpy as np
import os
k=[]
file1=open("TextData.txt",'w')
fn=input("Enter filename : ")
img=cv2.imread(fn,cv2.IMREAD_GRAYSCALE)
l=len(img)
w=len(img[0])
print(str(l)+"\n"+str(w))
for i in range(len(img)):
for j in range(len(img[0])):
k.append(img[i,j])
for a in range(len[k]):
file1.write(str(k[a])+"\n")
file1.close()
Basically, I'm running into the error :
Traceback (most recent call last):
File "imagereads.py", line 17, in <module>
for a in range(len[k]):
TypeError: 'builtin_function_or_method' object is not subscriptable
I'm trying to write a program that will store each image data in a file and access that later on when needed. Can anyone help me in this ? I'm doing this so that I can directly use file1.readLines() to read each data later on.
At first I tried appending each element to k, converting to a string and storing it directly. But I'm having problems getting back the data from the file into a list. Any help on this matter too will be appreciated.

Proper Use Of Python 3.x AMFY Module

How am I supposed to use the Amfy module? I try to use it like the JSON module (amfy.loads or amfy.load), but it just gives me errors:
C:\Users\Other>"C:\Users\Other\Desktop\Python3.5.2\test amf.py"
Traceback (most recent call last):
File "C:\Users\Other\Desktop\Python3.5.2\test amf.py", line 4, in <module>
print(amfy.load(cn_rsp.text))
File "C:\Users\Other\Desktop\Python3.5.2\lib\site-packages\amfy\__init__.py", line 9, in load
return Loader().load(input, proto=proto)
File "C:\Users\Other\Desktop\Python3.5.2\lib\site-packages\amfy\core.py", line 33, in load
return self._read_item3(stream, context)
File "C:\Users\Other\Desktop\Python3.5.2\lib\site-packages\amfy\core.py", line 52, in _read_item3
marker = stream.read(1)[0]
AttributeError: 'str' object has no attribute 'read'
this is what I wrote:
import requests
import amfy
cn_rsp = requests.get("http://realm498.c10.castle.rykaiju.com/api/locales/en/get_serialized_new")
print(amfy.load(cn_rsp.text))
After tinkering around and googling some stuff, I found a fix:
New code:
import amfy, requests, json
url = "http://realm416.c9.castle.rykaiju.com/api/locales/en/get_serialized_static"
req = requests.get(url)
if req.status_code == 200:
ret = req.json() if "json" in req.headers["content-type"] else amfy.loads(req.content)
else:
ret = {"failed": req.reason}
with open ("doa manifest.txt", 'w', encoding = 'utf-8') as dump:
json.dumps(ret, dump)
The Terminal throws a UnicodeEncodeError, but I was able to fix that by entering chcp 65001 and then set PYTHONIOENCODING=utf-8
The load method expects an input stream, you provide it a string. Just convert your string into a memory buffer which supports read method like this:
import io
print(amfy.load(io.BytesIO(cn_rsp.text.encode())))
unfortunately serialization fails when using this. Is there another url where it would work, a test URL maybe?
File "C:\Python34\lib\site-packages\amfy\core.py", line 146, in _read_vli
byte = stream.read(1)[0]
IndexError: index out of range

Resources