Dll load failed, in python 2.7 running on windows 8.1 - python-2.7

I'am using Boneh-Lynn-Shacham Identity Based Signature scheme for my final year project for getting encryption keys
from charm.toolbox.pairinggroup import *
from charm.engine.util import *
debug = False
class IBSig():
def __init__(self, groupObj):
global group
group = groupObj
def dump(self, obj):
ser_a = serializeDict(obj, group)
return str(pickleObject(ser_a))
def keygen(self, secparam=None):
g, x = group.random(G2), group.random()
g_x = g ** x
pk = { 'g^x':g_x, 'g':g, 'identity':str(g_x), 'secparam':secparam }
sk = { 'x':x }
return (pk, sk)
def sign(self, x, message):
M = self.dump(message)
if debug: print("Message => '%s'" % M)
return group.hash(M, G1) ** x
def verify(self, pk, sig, message):
M = self.dump(message)
h = group.hash(M, G1)
if pair(sig, pk['g']) == pair(h, pk['g^x']):
return True
return False
def main():
groupObj = PairingGroup('../param/d224.param')
m = { 'a':"hello world!!!" , 'b':"test message" }
bls = IBSig(groupObj)
(pk, sk) = bls.keygen(0)
sig = bls.sign(sk['x'], m)
if debug: print("Message: '%s'" % m)
if debug: print("Signature: '%s'" % sig)
assert bls.verify(pk, sig, m)
if debug: print('SUCCESS!!!')
if __name__ == "__main__":
debug = True
main()
when I am implementing it in python the code was not able to find the module named pairing though I have added Charm module to my library.Getting error like
Traceback (most recent call last):
File "C:\Users\Sailesh\Desktop\bls.py", line 1, in <module>
from charm.toolbox.pairinggroup import *
File "C:\Python27\lib\charm\toolbox\pairinggroup.py", line 2, in <module>
from charm.core.math.pairing import serialize
ImportError: DLL load failed: The specified module could not be found.
I have taken the code from
Boneh-Lynn-Shacham Identity Based Signature code and downloaded the module charm from charm module link. Let me know where is the error or whether the
problem is with the module. I cant figure out what is the problem. Thanks in advance.

Try the 0.43 version directly fron github:
https://github.com/JHUISI/charm/releases

Related

Dependent component can't be instantiated in AbstractModel with Pyomo >= 5.7.3

The following code does work on Pyomo 5.7.0, but does not work on Pyomo 5.7.3 and above anymore. The Error is "ValueError: Error retrieving immutable Param value (battery.n_time_steps)" (full traceback at the end) when trying to build the time_steps set.
import pyomo.environ as pyo
def test_param_pyomo5_7():
def create_battery():
block = pyo.Block()
block.n_time_steps = pyo.Param(within=pyo.NonNegativeIntegers, doc='Number of time steps')
block.time_steps = pyo.RangeSet(1, block.n_time_steps, doc='Time steps')
return block
def create_model() -> pyo.AbstractModel:
model = pyo.AbstractModel()
model.battery = create_battery()
return model
data = {
None: {
'battery': {
'n_time_steps': {None: 24},
},
}
}
model = create_model()
instance = model.create_instance(data=data)
The full traceback is:
..\..\opt\Miniconda3\envs\tesca_optimizer\lib\site-packages\pyomo\core\base\PyomoModel.py:697: in create_instance
instance.load( data,
..\..\opt\Miniconda3\envs\tesca_optimizer\lib\site-packages\pyomo\core\base\PyomoModel.py:734: in load
self._load_model_data(dp,
..\..\opt\Miniconda3\envs\tesca_optimizer\lib\site-packages\pyomo\core\base\PyomoModel.py:787: in _load_model_data
self._initialize_component(modeldata, namespaces, component_name, profile_memory)
..\..\opt\Miniconda3\envs\tesca_optimizer\lib\site-packages\pyomo\core\base\PyomoModel.py:825: in _initialize_component
declaration.construct(data)
..\..\opt\Miniconda3\envs\tesca_optimizer\lib\site-packages\pyomo\core\base\block.py:2207: in construct
obj.construct(data.get(name, None))
..\..\opt\Miniconda3\envs\tesca_optimizer\lib\site-packages\pyomo\core\base\disable_methods.py:116: in construct
return base.construct(self, data)
..\..\opt\Miniconda3\envs\tesca_optimizer\lib\site-packages\pyomo\core\base\set.py:2792: in construct
args = tuple(value(arg) for arg in args)
..\..\opt\Miniconda3\envs\tesca_optimizer\lib\site-packages\pyomo\core\base\set.py:2792: in <genexpr>
args = tuple(value(arg) for arg in args)
pyomo\core\expr\numvalue.pyx:153: in pyomo.core.expr.numvalue.value
???
pyomo\core\expr\numvalue.pyx:138: in pyomo.core.expr.numvalue.value
???
..\..\opt\Miniconda3\envs\tesca_optimizer\lib\site-packages\pyomo\core\base\param.py:853: in __call__
return self[None]
..\..\opt\Miniconda3\envs\tesca_optimizer\lib\site-packages\pyomo\core\base\indexed_component.py:577: in __getitem__
return self._getitem_when_not_present(index)
There was an inconsistency in how blocks were initialized from dictionary data in Pyomo<5.7.2, which was fixed in 5.7.2 (PR #1703). The correct data dictionary requires "indices" for all components (even scalar components). Your data dictionary is missing the None key (implicit index) for the data associated with the scalar Block battery. The following data dictionary will work in recent versions of Pyomo:
data = {
None: {
'battery': {
None: {
'n_time_steps': {None: 24},
},
},
}
}

python when there is no input for the subscriber it starts publishing error?/! how to solve it?

I have provided the following python code,but the problem is that when it doesnot receive any input, it start showing error. how can i modify the code in a way that this error dosnot appear:
#!/usr/bin/env python from roslib import message import rospy import sensor_msgs.point_cloud2 as pc2 from sensor_msgs.msg import PointCloud2, PointField import numpy as np import ros_numpy from geometry_msgs.msg import Pose
#listener def listen():
rospy.init_node('listen', anonymous=True)
rospy.Subscriber("/Filtered_points_x", PointCloud2, callback_kinect)
def callback_kinect(data):
pub = rospy.Publisher('lidar_distance',Pose, queue_size=10)
data_lidar = Pose()
xyz_array = ros_numpy.point_cloud2.pointcloud2_to_xyz_array(data)
print(xyz_array)
mini_data = min(xyz_array[:,0])
print("mini_data", mini_data)
data_lidar.position.x = mini_data
pub.publish(data_lidar)
print("data_points", data_lidar.position.x)
height = int (data.height / 2)
middle_x = int (data.width / 2)
middle = read_depth (middle_x, height, data) # do stuff with middle
def read_depth(width, height, data) :
if (height >= data.height) or (width >= data.width) :
return -1
data_out = pc2.read_points(data, field_names= ('x','y','z'), skip_nans=True, uvs=[[width, height]])
int_data = next(data_out)
rospy.loginfo("int_data " + str(int_data))
return int_data
if __name__ == '__main__':
try:
listen()
rospy.spin()
except rospy.ROSInterruptException:
pass
the following is the error that i mentioned:
[[ 7.99410915 1.36072445 -0.99567264]]
('mini_data', 7.994109153747559)
('data_points', 7.994109153747559)
[INFO] [1662109961.035894]: int_data (7.994109153747559, 1.3607244491577148, -0.9956726431846619)
[]
[ERROR] [1662109961.135572]: bad callback: <function callback_kinect at 0x7f9346d44230>
Traceback (most recent call last):
File "/opt/ros/kinetic/lib/python2.7/dist-packages/rospy/topics.py", line 750, in _invoke_callback
cb(msg)
File "/home/masoumeh/catkin_ws/src/yocs_velocity_smoother/test4/distance_from_pointcloud.py", line 27, in callback_kinect
mini_data = min(xyz_array[:,0])
ValueError: min() arg is an empty sequence
The code is still receiving input, but specifically it’s receiving an empty array. You’re then trying to splice the empty array, causing the error. Instead you should check that the array has elements before the line min(xyz_array[:,0]). It can be as simple as:
if xyz_array == []:
return
As another note, you’re creating a publisher in the callback. You shouldn’t do this as a new publisher will be created every time it gets called. Instead create it as a global variable.

Error exchanging list of floats in a topic

I think that the issue is silly.
I'd like to run the code on two computers and I need to use a list. I followed this Tutorials
I used my PC as a talker and computer of the robot as a listener.
when running the code on my PC, the output is good as I needed.
[INFO] [1574230834.705510]: [3.0, 2.1]
[INFO] [1574230834.805443]: [3.0, 2.1]
but once running the code on the computer of the robot, the output is:
Traceback (most recent call last):
File "/home/redhwan/learn.py", line 28, in <module>
talker()
File "/home/redhwan/learn.py", line 23, in talker
pub.publish(position.data)
File "/opt/ros/kinetic/lib/python2.7/dist-packages/rospy/topics.py", line 886, in publish
raise ROSSerializationException(str(e))
rospy.exceptions.ROSSerializationException: <class 'struct.error'>: 'required argument is not a float' when writing 'data: [3.0, 2.1]'
full code on PC:
#!/usr/bin/env python
import rospy
from std_msgs.msg import Float32
x = 3.0
y = 2.1
def talker():
# if a == None:
pub = rospy.Publisher('position', Float32, queue_size=10)
rospy.init_node('talker', anonymous=True)
# rospy.init_node('talker')
rate = rospy.Rate(10) # 10hz
while not rospy.is_shutdown():
position = Float32()
a = [x,y]
# a = x
position.data = list(a)
# position.data = a
# hello_str = [5.0 , 6.1]
rospy.loginfo(position.data)
pub.publish(position.data)
rate.sleep()
if __name__ == '__main__':
try:
talker()
except rospy.ROSInterruptException:
pass
full code on the computer of the robot:
#!/usr/bin/env python
import rospy
from std_msgs.msg import Float32
def callback(data):
# a = list(data)
a = data.data
print a
def listener():
rospy.init_node('listener', anonymous=True)
rospy.Subscriber("position", Float32, callback)
# spin() simply keeps python from exiting until this node is stopped
rospy.spin()
if __name__ == '__main__':
listener()
when using one number as float everything is OK.
I understand how to publish and subscribe to them separately as the float but I'd like to do it as list
Any ideas or suggestion, it would be appreciated.
When you exchange messages in ROS is preferred to adopt standard messages if there is something relatively simple. Of course, when you develop more sophisticated systems (or modules), you can implement your own custom messages.
So in the case of float array, Float32MultiArray is your friend.
Populating the message in one side will look like that (just an example using a 2 elements float32 array) in C++:
.
.
.
while (ros::ok())
{
std_msgs::Float32MultiArray velocities;
velocities.layout.dim.push_back(std_msgs::MultiArrayDimension());
velocities.layout.dim[0].label = "velocities";
velocities.layout.dim[0].size = 2;
velocities.layout.dim[0].stride = 1;
velocities.data.clear();
velocities.data.push_back(count % 255);
velocities.data.push_back(-(count % 255));
velocities_demo_pub.publish(velocities);
ros::spinOnce();
loop_rate.sleep();
++count;
}
.
.
.
in Python for 8 elements array an example will look like:
.
.
.
while not rospy.is_shutdown():
# compose the multiarray message
pwmVelocities = Float32MultiArray()
myLayout = MultiArrayLayout()
myMultiArrayDimension = MultiArrayDimension()
myMultiArrayDimension.label = "motion_cmd"
myMultiArrayDimension.size = 1
myMultiArrayDimension.stride = 8
myLayout.dim = [myMultiArrayDimension]
myLayout.data_offset = 0
pwmVelocities.layout = myLayout
pwmVelocities.data = [0, 10.0, 0, 10.0, 0, 10.0, 0, 10.0]
# publish the message and log in terminal
pub.publish(pwmVelocities)
rospy.loginfo("I'm publishing: [%f, %f, %f, %f, %f, %f, %f, %f]" % (pwmVelocities.data[0], pwmVelocities.data[1],
pwmVelocities.data[2], pwmVelocities.data[3], pwmVelocities.data[4], pwmVelocities.data[5],
pwmVelocities.data[6], pwmVelocities.data[7]))
# repeat
r.sleep()
.
.
.
and on the other side your callback (in C++), will look like:
.
.
.
void hardware_interface::velocity_callback(const std_msgs::Float32MultiArray::ConstPtr &msg) {
//velocities.clear();
if (velocities.size() == 0) {
velocities.push_back(msg->data[0]);
velocities.push_back(msg->data[1]);
} else {
velocities[0] = msg->data[0];
velocities[1] = msg->data[1];
}
vel1 = msg->data[0];
vel2 = msg->data[1];
//ROS_INFO("Vel_left: [%f] - Vel_right: [%f]", vel1 , vel2);
}
.
.
.
Hope that you got an idea...if you need something more drop me a line!

"AttributeError: class Frame has no attribute 'show_frame'"

this is my code for in which I am trying to link two pages
from Tkinter import *
class Example(Frame):
def __init__( self , parent, controller ):
Frame.__init__(self, parent)
self.controller=controller
self.parent = parent
self.parent.title("f2")
self.parent.configure(background="royalblue4")
self.pack(fill=BOTH, expand=1)
w = 800
h = 500
sw = self.parent.winfo_screenwidth()
sh = self.parent.winfo_screenheight()
x = (sw - w)/2
y = (sh - h)/2
self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
self.logbtn1 = Button(self,text="SIGN UP",font=("Copperplate Gothic Bold",16),bg=("dark green"),activebackground=("green"),command=lambda: controller.show_frame("D:\java prgms\minor\signup"))
self.logbtn1.place(x=325,y=175)
self.logbtn2 = Button(self, text="LOGIN",font=("Copperplate Gothic Bold",16),bg=("cyan"),activebackground=("yellow"),command=lambda: controller.show_frame("D:\java prgms\minor\log1"))
self.logbtn2.place(x=335,y=220)
self.pack()
def main():
root = Tk()
ex = Example(root,Frame)
root.mainloop()
if __name__ == '__main__':
main()
But here I am getting this error message:
AttributeError: class Frame has no attribute 'show_frame'
how to remove this error
First of all, you can not call lambda the way you did in command=lambda: controller.show_frame(...).
Suppose you did the necessary imports that I do not see in your current program, just replace those 2 statements (in 2 lines of your code) by : command=controller.show_frame(...).
Please read about how to use lambda
Second, your code contains an other error around this line:
if name == 'main':
main()
Change it to:
if __name__ == '__main__':
main()
After I fixed your error, I run your program successfully:
P.S. May be you would be interested in this post: What does if __name__ == "__main__": do?

loading a pickle file

I'm trying to get a "getting started with pickles" script working. I managed to save a pickle file from a file, and load it. But when I save a pickle file in one file (the main.py in this case) and load it from another, I get an error. I probably missed something small, but can't figure out what.
main.py
import pickle
class Node:
"""This class represents a node"""
def __init__(self, value = None):
self.val = value
def toString(self):
return self.val
class Link:
"""This class represents a link between 2 nodes"""
def __init__(self, sourceNode, targetNode, LinkWigth):
self.source = sourceNode
self.target = targetNode
self.wight = LinkWigth
def setWeight(self, newWeight):
self.wight = newWeight
def toString(self):
return self.wight
class Graph:
"""This class represents a graph"""
def __init__(self):
self.nodes = []
self.links = []
def addNode(self, node):
self.nodes.append(node)
def addLink(self, link):
self.links.append(link)
def getInDegree(self, node):
counter = 0
for link in self.links:
if link.target == node:
counter +=1
else:
print "target is: %s" % link.target.toString()
print "source is: %s" % link.source.toString()
return counter
def toString(self):
for link in self.links:
print link.toString()
for node in self.nodes:
print node.toString()
if __name__ == "__main__":
n1 = Node(4)
l1 = Link(n1, n1, 1)
g = Graph()
g.addNode(n1)
g.addLink(l1)
pickle.dump(g, open('haha', 'wb') )
pickleLoader.py
import pickle
import main
n = main.Node(44)
print n.toString()
g = pickle.load( open('haha', 'rb') )
print "ha"
The error
C:\Users\R\Desktop\pickle test>main.py
C:\Users\R\Desktop\pickle test>pickleLoader.py
44
Traceback (most recent call last):
File "C:\Users\R\Desktop\pickle test\pickleLoader.py", line 7, in <module>
g = pickle.load( open('haha', 'rb') )
File "C:\Program Files\Python27\lib\pickle.py", line 1378, in load
return Unpickler(file).load()
File "C:\Program Files\Python27\lib\pickle.py", line 858, in load
dispatch[key](self)
File "C:\Program Files\Python27\lib\pickle.py", line 1069, in load_inst
klass = self.find_class(module, name)
File "C:\Program Files\Python27\lib\pickle.py", line 1126, in find_class
klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'Graph'
C:\Users\R\Desktop\pickle test>
I guess that the problem is something with the namespace because main.py has been imported, but I have no idea how to get it working.
This does appear to be related to how the classes are defined in relation to the module. A quick way to allow this to work is to import the components of the main module directly into pickleLoader:
from main import Graph, Node, Link
A better solution might be to move the common components (Graph, Node, Link) into their own module, and then import that module into both main and pickleLoader.