how to solve classes parameter "self" - python

I tried to execute the code to create class as client but the problem display talk about the Self._public_key is not defined
...NameError: name 'self' is not defined
# import libraries
import hashlib
import random
import string
import json
import binascii
import numpy as np
import pandas as pd
import pylab as pl
import logging
import datetime
import collections
# following imports are required by PKI
import Crypto
import Crypto.Random
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
class Client:
def __init__(self):
random = Crypto.Random.new().read
self._private_key = RSA.generate(1024, random)
self._public_key = self._private_key.publickey()
self._signer = PKCS1_v1_5.new(self._private_key)
def identity(self):
return
binascii.hexlify(self._public_key.exportKey(format='DER')).decode('ascii')
Dinesh = Client()
print (Dinesh.identity)

You are writing binascii.hexlify(self._public_key.exportKey(format='DER')).decode('ascii') at the next line. Try writing it after the return keyword. Hope your error will go away

you should define a Clinet instance and then get it's _public_key:
binascii.hexlify(Client._public_key.exportKey(format='DER')).decode('ascii')

You need to get the identity property with the help of a function, not as a plain attribute. Modify your identity() function as follows:
def identity(self):
idn = binascii.hexlify(self._public_key.exportKey(format='DER')).decode('ascii') # <------
return idn # <------
And then, you can call it like:
Dinesh = Client()
print(Dinesh.identity()) # <------

Related

Importing a deck in anki python

I am working on an addon, for anki, which requires me to import a new deck using its python API. I found the function called test_apkg which seems to have parts which do that. I tried implimenting that below, I am getting no errors, however the deck does not get imported. How do I make my testFunction() import a deck for anki?
from aqt import mw
from aqt.utils import showInfo, qconnect
from aqt.qt import *
from anki.importing import *
import os
from anki.collection import Collection as aopen
#from anki.pylib.tests.shared import getEmptyCol
from .shared import getEmptyCol
def testFunction() -> None:
file = "flashcards.apkg"
col = getEmptyCol()
apkg = r"path_to_file/flashcards.apkg"
imp = AnkiPackageImporter(col, apkg)
imp.run()
# create a new menu item, "test"
action = QAction("Import", mw)
# set it to call testFunction when it's clicked
qconnect(action.triggered, testFunction)
# and add it to the tools menu
mw.form.menuTools.addAction(action)

Can't import helper functions from module - "cannot import name ..." error

I have two scripts, a main file and a smaller module storing some helper functions. My main script opens with
from collections import namedtuple
import rospy
import serial
from sensor_msgs.msg import Imu, MagneticField
from quaternions import euler_deg2rad, euler2quat_ZYX
and in quaternions.py, I have
from collections import namedtuple
import numpy as np
def euler_deg2rad(yaw, pitch, roll):
....
Attempting to run the main script throws an ImportError: cannot import name 'euler_deg2rad' from 'quaternions'
What's going on here? Is importing namedtuple twice creating a circular dependency? Replacing the 'from' import in the main file with just import quaternions works fine, but I'd rather not import the whole module.

Is this the right way to "publish" msg to the topic?

Currently learning ROS with LGSVL Simulator. I want to publish to "/move_base_simple/goal" topic.
In main code just showing important "import" and the end of the code
import rospy
import roslibpy
from rospy import rostime
import lgsvl
import logging
from environs import Env
from geometry_msgs.msg import PoseStamped
import publisher
### LGSVL SETUP ###
...
###################
ego.set_destination(publisher.GoalPublisher.publish_2d_nav_goal(self=publisher.GoalPublisher,pose_x=9425.16015625, pose_y=9823.15527344, pose_z=0.0))
ros = roslibpy.Ros(host='localhost', port=9090)
ros.run()
sim.run()
This is my publisher
import rospy
import rospkg
import std_msgs
from geometry_msgs.msg import PoseStamped
class GoalPublisher():
def __init__(self):
rospy.init_node('webapp', disable_signals=True)
self.goal_publisher = rospy.Publisher("move_base_simple/goal", PoseStamped, queue_size=10)
def publish_2d_nav_goal(self, pose_x, pose_y, pose_z):
goal = PoseStamped()
goal.header.stamp = rospy.Time.now()
goal.header.frame_id = "map"
goal.pose.position.x = pose_x
goal.pose.position.y = pose_y
goal.pose.position.z = pose_z
goal.pose.orientation.x = 0.0
goal.pose.orientation.y = 0.0
goal.pose.orientation.z = -0.663932738254
goal.pose.orientation.w = 0.747792296747
self.goal_publisher.publish(goal)
When i am trying to start my main code, i get this error:rospy.exceptions.ROSInitException: time is not initialized. Have you called init_node()?
Do i need to add "rospy.init_node(...)" in the main code ? Or how can i fix this issue ?
You need to call rospy.init_node() for every ros node you create. You can call it wherever you want in the node, however, it must be called before trying to use anything in the ros api. In this example your publisher is fine but you're calling roslibpy.Ros() before initializing the main code as it's own node.
rospy.init_node('main_node')
ego.set_destination(publisher.GoalPublisher.publish_2d_nav_goal(self=publisher.GoalPublisher,pose_x=9425.16015625, pose_y=9823.15527344, pose_z=0.0))
ros = roslibpy.Ros(host='localhost', port=9090)
ros.run()
sim.run()

Python Class Initialization Error. Cannot initialize an Imported class

I am trying to initialize a class ModuleLMPC from commander.py which is the main class. I get following error.
File "D:\CARLA\PythonAPI\examples\fnc\commander.py", line 89, in __init__
self.LMPC = ModuleLMPC(self.dt, self.LapTime, self.maxLaps, self.Map)
TypeError: 'module' object is not callable
I import ModuleLMPC as:
from ModuleLMPC import ModuleLMPC
I am trying to import ModuleLMPC from ModuleLMPC.py file. They have the same name.
The ModuleLMPC first few lines look like:
from SysModel import Simulator, PID
from Classes import ClosedLoopData, LMPCprediction
from PathFollowingLTVMPC import PathFollowingLTV_MPC
from PathFollowingLTIMPC import PathFollowingLTI_MPC
from LMPC import ControllerLMPC
from Utilities import Regression
import numpy as np
import pdb
import pickle
class ModuleLMPC(object):
def __init(self, dt, Time, maxlaps, map):
# ======================================================================================================================
# ============================ Choose which controller to run ==========================================================
# ======================================================================================================================
self.RunPID = 1
self.RunMPC = 1
And I initialize ModuleLMPC in commander.py as:
self.LMPC = ModuleLMPC(self.dt, self.LapTime, self.maxLaps, self.Map)
I even moved everything in the same folder. Not sure what the error means.

How to trigger a function without importing everything?

I programmed a gateway to a opcua-server with python-opcua.
The gateway is subscribing some values in the opcua. That is working good and fast.
Now I want to call a script that writes to the opcua.
In principle, it works too. But because I have to import the whole gateway(and all opcua stuff), it is very slow...
My Question: Is is possible to trigger a function in my class-instance without imorting everything?
To start e.g. function setBool(), I have to import Gateway...
#!/usr/bin/env python3.5 -u
# -*- coding: utf-8 -*-
import time
import sys
import logging
from logging.handlers import RotatingFileHandler
from threading import Thread
from opcua import Client
from opcua import ua
from subscribeOpcua import SubscribeOpcua
from cmdHandling import CmdHandling
from keepConnected import KeepConnected
class Gateway(object):
def __init__(self):
OPCUA_IP = '1.25.222.222'
OPCUA_PORT = '4840'
OPCUA_URL = "opc.tcp://{}:{}".format(OPCUA_IP, str(OPCUA_PORT))
addr = "OPCUA-URL:{}.".format(OPCUA_URL)
# Setting up opcua-handler
self.client = Client(OPCUA_URL)
self.opcuaHandlers = [SubscribeOpcua()]
# Connect to opcua
self.connecter = KeepConnected(self.client,self.opcuaHandlers)
self.connecter.start()
def setBool(self, client):
"""Set e boolean variable on opcua-server.
"""
path = ["0:Objects","2:DeviceSet"...]
root = client.get_root_node()
cmd2opcua = root.get_child(path)
cmd2opcua.set_value(True)
if __name__ == "__main__":
"""Open connecter when gateway is opened directly.
"""
connect = Gateway()
The only way to prevent a code from runing when importing a module is to put it inside a method:
def import_first_part():
global re
global defaultdict
print('import this first part')
# import happen locally
# because when you do `import re` actually
# re = __import__('re')
import re
from collections import defaultdict
def import_second_part():
print('import pandas')
# really unnecessary check here because if we import
# pandas for the second time it will just retrieve the object of module
# the code of module is executed only in the first import in life of application.
if 'pandas' in globals():
return
global pandas
import pandas
def use_regex():
import_first_part()
# do something here
if __name__ == '__main__':
use_regex()
re.search('x', 'xb') # works fine
I checked that 'pandas' is in global scope before reimport it again but really this is not necessary, because when you import a module for the second time it's just retrieved no heavy calculation again.

Categories

Resources