Serializing and deserializing group elements in Charm-Crypto - python

I need help to convert the list representation (string) of elliptic curve pairing group element back to an object.
Explanation:
I am using charm crypto v0.43 to use CPABE scheme in my web application. I need to store the pairing element that is generated into my database. When I did that, it is storing it as list. I need to map it back to pairing group element object.
Convert:
[771281202364725359015275543519860265278248937600027018972741977722880288402810467924555583431036045929994018001453439703799448692568829067937466068366897, 5928426678871551838449004494119368314093842432141364739971117261348155912543962117516776973405646414105108743246860323245910977796691638669773215755592297]
to
<pairing.Element object at 0x7f1a1e840300>`
Code:
group = PairingGroup('SS512')
alpha = group.random(ZR)
g= group.random(G1)

Found a solution to my problem. Here is what i did.You can use groups serialize function.
g = group.random(G1) # generates a random group element in that pairing group
You can serialize g using groups serialize function:
str = group.serialize(g)
You can deserialize it using
obj = group.deserialize(str)
Hope it might help somebody facing the same issue.

Related

Get columns from generator object

I'm using Scrapetube to get videos from a channel, and it brings a generator object. From the very simple documentation, I know it includes the parameter "videoId", but how can I know what other parameters I can get from there? Can I transform a generator object into, say, a dataframe?
Generators allow you to efficiently iterate over (potentially infinite) sequences.
In your case, you probably want to first convert the generator into a list to expose all items in the sequence.
Then you can inspect what the returned elements look like and extract the information you need.
You can then create a dataframe for instance from a list of dictionaries:
result_gen = scrapetube.xxx()
result_list = list(result_gen)
# Inspect first element
print(result_list[0])
# Inspect attributes of the first element
print(dir(result_list[0]))
# Convert/extract information of interest into a dictionary
def to_dict(element):
...
result_df = pd.DataFrame([to_dict(element) for element in result_list])

How can I consume real-time data from alphavantage API in python's dictionary?

I try to use alphavantage API in my project. At the moment I am going to parse the JSON data in this way:
from alpha_vantage.timeseries import TimeSeries
def AlphaVantage(symbol):
ts = TimeSeries(key='mykey')
data = ts.get_intraday(symbol, interval='1min')
print(str(data))
AlphaVantage('MSFT')
I would like to get only the most current data.
The data returned is a tuple. There are two dictionaries inside the tuple. The first one contains the time and high/low values and the second contains the metadata. So, you can access the time:high/low values by data[0]. As you know that the keys in a dictionary are unsorted, so to only get the most recent data, you can use max of keys of this dictionary. So, the final code would be like this:
print(str(data[0][max(data[0].keys())]))
If the API does not provide it, you can just grab the first one as the data is obviously sorted by date:
print(str(data['Time Series (1min)'][0]))
Hope it helps!

Python/Django Referencing Nested JSON

I'm using the Google Places Reverse Geocode API to return the latitude and longatude of a given address. The API returns a massive JSON file with tons of nested objects. Here's Google's documentation on it.
I'm trying to grab the geometry.location.lat object (see documentation). Here's my current code, followed by the error it returns:
address_coords = gmaps.geocode(raw_address)
# gmaps makes the API request and returns the JSON into address_coords
address_lat = address_coords['results']['geometry']['location']['lat']
address_lon = address_coords['results']['geometry']['location']['lng']
TypeError: List indices must be integers or slices, not str
I'm not sure how to reference that JSON object.
The error is telling you that you're trying to index an array as if it were a property.
Most likely results is the array, so you'd need to do the following to get the value for the first item at index 0:
address_coords['results'][0]['geometry']['location']['lng']
The other possibility is that geometry contains multiple coordinates which you could similarly index:
address_coords['results']['geometry'][0]['location']['lng']
Either way, you should pretty print the structure to see which attributes are arrays versus dictionaries.
import pprint
pprint.pprint(address_coords)

Python, how to check object is in list?

I have an object to store data:
Vertex(key, children)
and a list to store this objects
vertices = []
im using another list
key_vertices = []
to store keys of my vertices, so i can easy access(withot looping every object), each time i need to check vertex with such key exist, like that:
if key not in self.key_vertices:
# add a new key to the array
self.key_vertices.append(key)
# create a vertex object to store dependency information
self.verteces.append(Vertex(key, children))
i think it a bit complicated, maybe someone now better way, to store multiple Vertices objects with ability easy to check and access them
Thanks
your example works fine, the only problem you could have is a performance issue with the in operator for list which is O(n).
If you don't care about the order of the keys (which is likely), just do this:
self.key_vertices = set()
then:
if key not in self.key_vertices:
# add a new key to the array
self.key_vertices.add(key)
# create a vertex object to store dependency information
self.verteces.append(Vertex(key, children))
you'll save a lot of time in the in operator because set in is way faster due to key hashing.
And if you don't care about order in self.verteces, just do a dictionary, and in that case, you probably don't need the first key parameter to your Vertex structure.
self.verteces = dict()
if key not in self.verteces:
# create a vertex object to store dependency information
self.verteces[key] = Vertex(children)
When you need to check for membership, a list is not the best choice as every object in the list will be checked.
If key is hashable, use a set.
If it's not hashable but is comparable, use a tree (unavailable in the standard library). Try to make it hashable.
If I understand correctly, you want to check if an element has already been added for O(1) (i.e. that you do not have to check every element in the list).
The easiest way to do that is use a set. A set is an unordered list that allows you to check if an element exists with a constant time O(1). You can think of a set like a dict with keys only but it works just like a list:
for value in mySet:
print(value)
print("hello" in mySet)
If you need an ordered list (most of the time, you don't), your approach is pretty good but I would use a set instead:
self.vertece_set = set() # Init somewhere else ;)
if key not in self.vertece_set:
# add a new key to the array
self.vertece_set.add(key)
# create a vertex object to store dependency information
self.verteces.append(Vertex(key, children))

Accessing Python object in tuple

I am using easyzone and dnspython to extract DNS records from a zone file. When extracting A records I am given back a string and an object in a tuple. I am new to Python coming from PHP and am not quite sure how to get at this object to get the value of it? I had no problems getting the string value in the tuple.
In this code snippet I iterate through the A records and write the values into a CSV:
# Write all A records
for a in z.names.items():
c.writerow([domain, 'A', a.__getitem__(0), a])
a contains the following:
('www.121dentalcare.com.', <easyzone.easyzone.Name object at 0x1012dd190>)
How would I access this object within a which is in the 2nd half of this tuple??
You can use indices to get items from a tuple:
sometuple[1]
just as you can do with lists and strings (see sequence types).
The documentation of easyzone is a little on the thin side, but from looking at the source code it appears the easyzone.easyzone.Name objects have .name, .soa and .ttl attributes:
print sometuple[1].name
The .soa attribute is another custom class, with .mname, .rname, .serial, .refresh, .retry, .expire and .minttl properties.

Categories