python Excel DDE input and translating it into Python - python

I am using "dde" package in Python and my Excel input is
=XXExcecute|'some_code_for_financial_products'!'field_name'
As you can see it has parenthesis around strings.
However, the problem is that I don't know how to "translate" the input to
dde module's function inputs.
I know that inside "Create", I should type in the "XXExecute" part but
don't know what to pass in ConnectTo, given the Excel input is what I mentioned above.
and this function is where my code failed, giving me this messages:
c.ConnectTo("'P10102'","'9001'")
dde.error: ConnectTo failed
the entire code is as follows:
import win32ui
import dde
import pandas as pd
#making an instance
server = dde.CreateServer()
#executing instance
server.Create("XXExecute")
#DDEconversation
c= dde.CreateConversation(server)
c.ConnectTo('X10102','')
#or I tried to pass in ('X10102','9001') but it failed as well.
c.Connected()
c.Request("9001")

Related

How to build CDK Assembly using Python aws_cdk.cx_api

I'm desperate so any help is appreciated.
I'm trying to modify my current CDK out using cloud assembly in Python.
I can't find any examples, nor proper documentation for python, only reference guide.
This is my code:
import os
import subprocess
import aws_cdk.cx_api as cxapi
import aws_cdk.cloud_assembly_schema as cxschema
class my_class():
def synth():
ASSEMBLY_PATH = 'igor_cdk'
result = subprocess.run(['cdk', 'synth', '-o', ASSEMBLY_PATH], stdout=subprocess.PIPE)
my_stuff = result.stdout.decode('utf-8')
new_stack_name = original_stack_name+TEMP_OUT
print(new_stack_name)
cloud_assembly = cxapi.CloudAssembly(ASSEMBLY_PATH);
orig_stack_assembly = cloud_assembly.get_stack_by_name(original_stack_name)
logical_Ids = orig_stack_assembly.find_metadata_by_type("aws:cdk:logicalId")
cab = cxapi.CloudAssemblyBuilder(ASSEMBLY_PATH)
cab.add_artifact(new_stack_name, type = cxschema.ArtifactType.ASSET_MANIFEST, properties = orig_stack_assembly.manifest)
Then, In my dummy test, I call this:
print(stack_info.synth("Test", "Targeta"))
And that's executed with pytest.
Just for comparison, I got it working in Typescript:
const cab: CloudAssemblyBuilder = new CloudAssemblyBuilder(ASSEMBLY_PATH);
cab.addArtifact(new_stack_name, stack.manifest);
cab.buildAssembly();
I expected similar/same behavior, but I just can't figure out how to do it in python, and since my whole code base is in python, I'd just love to have it all done in one place, rather than reworking the whole thing in TS.
Edit:
If I pass the stack.manifest, I'm getting the following error:
jsii.errors.JSIIError: Value did not match any type in union:
Wire struct type '#aws-cdk/cloud-assembly-schema.ArtifactManifest' does not match expected '#aws-cdk/cloud-assembly-schema.AwsCloudFormationStackProperties', Wire struct type '#aws-cdk/cloud-assembly-schema.ArtifactManifest' does not match expected '#aws-cdk/cloud-assembly-schema.AssetManifestProperties',
Wire struct type '#aws-cdk/cloud-assembly-schema.ArtifactManifest' does not match expected '#aws-cdk/cloud-assembly-schema.TreeArtifactProperties',
Wire struct type '#aws-cdk/cloud-assembly-schema.ArtifactManifest' does not match expected '#aws-cdk/cloud-assembly-schema.NestedCloudAssemblyProperties'
And if I pass the whole stack assembly object, I run in even weirder problem:
jsii.errors.JavaScriptError:
RangeError: Maximum call stack size exceeded
at /private/var/folders/z6/c91mcs6j4g93t2856_p_51nr0000gn/T/jsii-kernel-35iS5M/node_modules/#aws-cdk/cx-api/lib/cloud-assembly.js:307:53

Unable to pass custom values to AWS Lambda function

I am trying to pass custom input to my lambda function (Python 3.7 runtime) in JSON format from the rule set in CloudWatch.
However I am facing difficulty accessing elements from the input correctly.
Here's what the CW rule looks like.
Here is what the lambda function is doing.
import sqlalchemy # Package for accessing SQL databases via Python
import psycopg2
def lambda_handler(event,context):
today = date.today()
engine = sqlalchemy.create_engine("postgresql://some_user:userpassword#som_host/some_db")
con = engine.connect()
dest_table = "dest_table"
print(event)
s={'upload_date': today,'data':'Daily Ingestion Data','status':event["data"]} # Error points here
ingestion = pd.DataFrame(data = [s])
ingestion.to_sql(dest_table, con, schema = "some_schema", if_exists = "append",index = False, method = "multi")
When I test the event with default test event values, the print(event) statement prints the default test values ("key1":"value1") but the syntax for adding data to the database ingestion.to_sql() i.e the payload from input "Testing Input Data" is inserted to the database successfully.
However the lambda function still shows an error while running the function at event["data"] as Key error.
1) Am I accessing the Constant JSON input the right way?
2) If not then why is the data still being ingested as the way it is intended despite throwing an error at that line of code
3) The data is ingested when the function is triggered as per the schedule expression. When I test the event it shows an error with the Key. Is it the test event which is not similar to the actual input which is causing this error?
There is alot of documentation and articles on how to take input but I could not find anything that shows how to access the input inside the function. I have been stuck at this point for a while and it frustrates me that why is this not documented anywhere.
Would really appreciate if someone could give me some clarity to this process.
Thanks in advance
Edit:
Image of the monitoring Logs:
[ERROR] KeyError: 'data' Traceback (most recent call last): File "/var/task/test.py"
I am writing this answer based on the comments.
The syntax that was originally written is valid and I am able to access the data correctly. There was a need to implement a timeout as the function was constantly hitting that threshold followed by some change in the iteration.

How can I find the required parameters for a function imported from a DLL file using ctypes?

I'm trying to run some motor controllers using a library supplied by Maxon. The library is a DLL file that I'm reading in using ctypes and pythonNet. The library is working, I can drive the motors and most functions I've used so far have been fine. However, to read position data back from the controller I need to use a function called VcsGetObject. Every call I've made to the function has resulted in an error because I don't have the proper inputs or outputs:
TypeError: No method matches given arguments for VcsGetObject
The VcsGetObject function accepts a data input by reference and returns position data through that variable. I've tried various methods of passing data to the function but haven't been successful yet. I've tried giving the function extra outputs, since I've read that PythonNet can do that automatically. I've tried passing in tuples or lists, or passing ctypes datatypes using ctypes.byref().
I'm honestly not sure where the problem is, and I want to know if there's some way to look at what the function expects in. I have documentation for the C++ function, but since I'm importing it from a DLL I can't really tell where the problem is. I apologize for the vagueness of this question, I honestly feel like there are so many places this could be going wrong but maybe there's something really obvious I just don't know about.
import time
import clr #pythonnet, manually installed with a downloaded wheel and pip
import ctypes #module to open dll files
import System
clr.AddReference('EposCmd.Net')
EposCmd64 = ctypes.CDLL('.\EposCmd64.dll')
from EposCmd.Net.VcsWrapper import Device
print("START")
print()
Device.Init()
nodeID = 1
baudrate = 1000000
timeout = 500
errorCode = 0
index = int('0x606C',16)
subindex = 0
dataLength = 4
# These functions all work as expected, so the library is being imported correctly
keyHandle, error = Device.VcsOpenDevice('EPOS4', 'MAXON SERIAL V2', 'USB', 'USB0', errorCode) #opens EPOS
print(errorCode)
Device.VcsSetProtocolStackSettings(keyHandle, baudrate, timeout, errorCode) #set baudrate
Device.VcsClearFault(keyHandle, nodeID, errorCode) #clear all faults
# # Trying to use lists or tuples doesn't work
#data = [0]
#readLength = [0]
#output = Device.VcsGetObject(keyHandle,nodeID,index,subindex,data,readLength,errorCode)
# # Using ctypes and .byref(), also doesn't work
#data = ctypes.c_byte()
#readLength = ctypes.c_byte()
#output = Device.VcsGetObject(keyHandle,nodeID,index,subindex,ctypes.byref(data),ctypes.byref(readLength),errorCode)
# # Trying to use PythonNet to turn by ref inputs into outputs
output, data, readLength = Device.VcsGetObject(keyHandle,nodeID,index,subindex,errorCode)
#print(data)
#print(readLength)
I've included links to the maxon documentation, GetObject is in section 4.1.4.
https://www.maxongroup.com/medias/sys_master/8823917281310.pdf
Firstly, your function calls looks incorrect. This is untested, but your open device call should look more like:
from ctypes import byref, c_byte, c_void_p
from ctypes.wintypes import WORD, DWORD
# Set type
errorCode = DWORD()
# Pass error by reference
handle = Device.VcsOpenDevice(
'EPOS4',
'MAXON SERIAL V2',
'USB',
'USB0',
byref(errorCode))
# Read error code after function call
print(errorCode.value)
According to your linked doc VCS_GetObject looks like this:
nodeId = WORD(1)
objectIndex = WORD(0x606C)
objectSubIndex = c_byte(0)
NbOfBytesToRead = DWORD(
data = c_void_p()
# Vary this to read more or less data
NbOfBytesToRead = DWORD(4)
NbOfBytesRead = DWORD()
errorCode = DWORD()
return_value = Device.VcsGetObject(
handle,
nodeId,
objectIndex,
objectSubIndex,
byref(data),
NbOfBytesToRead,
byref(NbOfBytesRead),
byref(errorCode))
print(errorCode.value)
You should also set your restype and argtypes.

How to assign a 2d libreoffice calc named range to a python variable. Can do it in Libreoffice Basic

I can't seem to find a simple answer to the question. I have this successfully working in Libreoffice Basic:
NamedRange = ThisComponent.NamedRanges.getByName("transactions_detail")
RefCells = NamedRange.getReferredCells()
Set MainRange = RefCells.getDataArray()
Then I iterate over MainRange and pull out the rows I am interested in.
Can I do something similar in a python macro? Can I assign a 2d named range to a python variable or do I have to iterate over the range to assign the individual cells?
I am new to python but hope to convert my iteration intensive macro function to python in hopes of making it faster.
Any help would be much appreciated.
Thanks.
LibreOffice can be manipulated from Python with the library pyuno. The documentation of pyuno is unfortunately incomplete but going through this tutorial may help.
To get started:
Python-Uno, the library to communicate via Uno, is already in the LibreOffice Python’s path. To initialize your context, type the following lines in your python shell :
import socket # only needed on win32-OOo3.0.0
import uno
# get the uno component context from the PyUNO runtime
localContext = uno.getComponentContext()
# create the UnoUrlResolver
resolver = localContext.ServiceManager.createInstanceWithContext(
"com.sun.star.bridge.UnoUrlResolver", localContext )
# connect to the running office
ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
smgr = ctx.ServiceManager
# get the central desktop object
desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
# access the current writer document
model = desktop.getCurrentComponent()
Then to get a named range and access the data as an array, you can use the following methods:
NamedRange = model.NamedRanges.getByName(“Test Name”)
MainRange = NamedRange.getDataArray()
However I am unsure that this will result in a noticeable preformance gain.

Python numpy library log method returning wrong value

Python numpy library log method returning wrong value so please help me.
import numpy as np
print('Log :',np.log(0.25))
numpy log method returns -1.38629436112
Excel log function =LOG(0.25) returns -0.602059991327962
Then I Calculated manually using calculator it returns -0.602059991327962.
Because the log function is in base e while your calculator and excel are base 10 by default. Use np.log10(0.25) and you'll get the value you want.

Categories

Resources