Skip to content

Instantly share code, notes, and snippets.

@BookOwl
Created April 3, 2016 01:41
Show Gist options
  • Save BookOwl/6c831dcfeee799969c67928adefd1a4b to your computer and use it in GitHub Desktop.
Save BookOwl/6c831dcfeee799969c67928adefd1a4b to your computer and use it in GitHub Desktop.
cloudcoder.py - Python module to go along with https://scratch.mit.edu/projects/103348115/
"""cloudcoder.py - Utilities for encoding and decoding strings for Scratch cloud data
Use the encode and decode functions to prepare strings to be stored in cloud variables
and to get strings out of them.
Examples:
>>> encode("I <3 the cloud")
'0x2F49203c332074686520636c6f7564'
>>> decode('0x2F49203c332074686520636c6f7564')
'I <3 the cloud'
cloudcoder.py is released under the MIT license."""
def group(it, n):
"""Splits an iterable (it) into n length sections
>>> list(group("123456789", 3))
['123', '456', '789']
>>> list(group("123456789ab", 3))
['123', '456', '789', 'ab']
"""
while it:
yield it[:n]
it = it[n:]
def encode(string):
"""Encodes string using my cloud data encoding system.
The return value of this function can be directly stored in a cloud variable.
>>> encode("Hello, World!")
'0x2F48656c6c6f2c20576f726c6421'
>>> encode("Hello to the ☁ ☁ ☁")
'0x4F00480065006c006c006f00200074006f0020007400680065002026010020260100202601'
"""
chars = [hex(ord(c))[2:] for c in string]
longest = max(map(len, chars))
chars = "".join(c.rjust(longest, "0") for c in chars)
return "0x%sF%s" % (longest, chars)
def decode(string):
"""Decodes string using my cloud data encoding system.
>>> decode('0x2F48656c6c6f2c20576f726c6421')
'Hello, World!'
>>> decode('0x4F00480065006c006c006f00200074006f0020007400680065002026010020260100202601')
'Hello to the ☁ ☁ ☁'
"""
longest, enc = string[2:].split("F")
chars = group(enc, int(longest))
return "".join(chr(int(c, base=16)) for c in chars)
@prail
Copy link

prail commented Sep 12, 2016

Thanks for this. It makes my heart glad.

@InCrIpTiOn
Copy link

But how can you change cloud variables of a project using python?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment