def test_docs_table_any(): class Table(object): def __init__(self, height, width): self.height = height self.width = width def __repr__(self): return "<Table {self.height!r}x{self.width!r}>".format(self=self) from camel import Camel, CamelRegistry my_types = CamelRegistry() @my_types.loader('table', version=any) def _load_table(data, version): if 'size' in data: # version 1 edge = data['size']**0.5 return Table(edge, edge) else: # version 2?) return Table(data['height'], data['width']) camel = Camel([my_types]) table1, table2 = camel.load( "[!table;1 {size: 49}, !table;2 {height: 5, width: 9}]") assert table1.height == 7 assert table1.width == 7 assert table2.height == 5 assert table2.width == 9
def test_docs_table_any(): class Table(object): def __init__(self, height, width): self.height = height self.width = width def __repr__(self): return "<Table {self.height!r}x{self.width!r}>".format(self=self) from camel import Camel, CamelRegistry my_types = CamelRegistry() @my_types.loader('table', version=any) def _load_table(data, version): if 'size' in data: # version 1 edge = data['size'] ** 0.5 return Table(edge, edge) else: # version 2?) return Table(data['height'], data['width']) camel = Camel([my_types]) table1, table2 = camel.load( "[!table;1 {size: 49}, !table;2 {height: 5, width: 9}]") assert table1.height == 7 assert table1.width == 7 assert table2.height == 5 assert table2.width == 9
def processAndSend(self, char, pos): position = [] if char == 'white:soldier' or char == 'black:soldier': sold = Soldier(char, pos) position = sold.getPositions() elif char == 'white:eleph' or char == 'black:eleph': elephant = Elephant(char, pos) position = elephant.getPositions() elif char == 'white:camel' or char == 'black:camel': cam = Camel(char, pos) position = cam.getPositions() elif char == 'white:horse' or char == 'black:horse': hors = Horse(char, pos) position = hors.getPositions() elif char == 'white:queen' or char == 'black:queen': qun = Queen(char, pos) position = qun.getPositions() elif char == 'white:king' or char == 'black:king': kin = King(char, pos) position = kin.getPositions() dataString = pickle.dumps(position) self.client.send(dataString)
def test_frozenset_roundtrip(): # By default, frozensets become sets value = frozenset((4, 3, 2)) camel = Camel() dumped = camel.dump(value) # TODO this should use ? notation assert dumped == "!!set\n2: null\n3: null\n4: null\n" assert camel.load(dumped) == set(value)
def test_python_roundtrip(value, expected_serialization): camel = Camel([PYTHON_TYPES]) dumped = camel.dump(value) assert dumped == expected_serialization # Should be able to load them without the python types vanilla_camel = Camel() assert vanilla_camel.load(dumped) == value
def test_tuple_roundtrip(): # By default, tuples become lists value = (4, 3, 2) camel = Camel() dumped = camel.dump(value) # TODO short list like this should be flow style? assert dumped == "- 4\n- 3\n- 2\n" assert camel.load(dumped) == list(value)
def load(): """Load config from fursuit.yaml""" global c try: with open("/boot/FursuitOS/fursuit.yaml") as f: c = Dict(Camel([caramel]).load(f.read())) return True except: c = Dict(Camel([caramel]).load(defaults)) return False
def test_docs_deleted(): class DummyData(object): def __init__(self, data): self.data = data from camel import Camel, CamelRegistry my_types = CamelRegistry() @my_types.loader('deleted-type', version=all) def _load_deleted_type(data, version): return DummyData(data) camel = Camel([my_types]) assert isinstance(camel.load("""!deleted-type;4 foo"""), DummyData)
def __new__(cls, name, bases, dct): attrs = ((name, value) for name, value in dct.items() if not name.startswith('__')) camelcase_attr = dict((Camel(name), value) for name, value in attrs) return super(CodeStyle, cls).__new__(cls, name, bases, camelcase_attr)
def test_docs_table_v2(): # Tables can be rectangles now! class Table(object): def __init__(self, height, width): self.height = height self.width = width def __repr__(self): return "<Table {self.height!r}x{self.width!r}>".format(self=self) from camel import Camel, CamelRegistry my_types = CamelRegistry() @my_types.dumper(Table, 'table', version=2) def _dump_table_v2(table): return { 'height': table.height, 'width': table.width, } @my_types.loader('table', version=2) def _load_table_v2(data, version): return Table(data["height"], data["width"]) @my_types.loader('table', version=1) def _load_table_v1(data, version): edge = data["size"] ** 0.5 return Table(edge, edge) table = Table(7, 10) assert Camel([my_types]).dump(table) == textwrap.dedent(""" !table;2 height: 7 width: 10 """).lstrip() @my_types.dumper(Table, 'table', version=1) def _dump_table_v1(table): return { # not really, but the best we can manage 'size': table.height * table.width, } camel = Camel([my_types]) camel.lock_version(Table, 1) assert camel.dump(Table(5, 7)) == "!table;1\nsize: 35\n"
def save(): """Save config to fursuit.yaml""" global c try: with open("/boot/FursuitOS/fursuit.yaml", "w") as f: f.write(Camel([caramel]).dump(c.to_dict())) return True except: return False
def test_docs_table_v1(): class Table(object): def __init__(self, size): self.size = size def __repr__(self): return "<Table {self.size!r}>".format(self=self) from camel import CamelRegistry my_types = CamelRegistry() @my_types.dumper(Table, 'table', version=1) def _dump_table(table): return { 'size': table.size, } @my_types.loader('table', version=1) def _load_table(data, version): return Table(data["size"]) from camel import Camel table = Table(25) assert Camel([my_types]).dump(table) == "!table;1\nsize: 25\n" data = {'chairs': [], 'tables': [Table(25), Table(36)]} assert Camel([my_types]).dump(data) == textwrap.dedent(""" chairs: [] tables: - !table;1 size: 25 - !table;1 size: 36 """).lstrip() table, = Camel([my_types]).load("[!table;1 {size: 100}]") assert isinstance(table, Table) assert table.size == 100
def regdump(): x = "\n=== Configuration ===\n" x += Camel([caramel]).dump(config.c.to_dict()) x += "\n=== Fursuit modules ===\n" x += pprint.pformat(fs) x += "\n=== User interface ===\n" x += pprint.pformat(ui) x += "\n=== Device tree ===\n" x += pprint.pformat(hw) x += "\n=== Process scheduler ===\n" x += pprint.pformat(proc) x += "\n=== Crontab ===\n" x += pprint.pformat(cron) x += "\n=== Network info ===\n" x += "Address: {0}\n".format(r.extget("ip")) x += "Gateway: {0}\n".format(r.extget("gateway")) return x
def get_inventory(self, topo, layout): layout = Camel().load(layout) # get all the topology host_ips host_ip_dict = self.get_host_ips(topo) # get the count of all layout hosts needed layout_host_count = self.get_layout_hosts(layout) # generate hosts list based on the layout host count inven_hosts = self.get_hosts_by_count(host_ip_dict, layout_host_count) # adding sections to respective host groups host_groups = self.get_layout_host_groups(layout) self.add_sections(host_groups) # set children for each host group self.set_children(layout) # set vars for each host group self.set_vars(layout) # add ip addresses to each host self.add_ips_to_groups(inven_hosts, layout) self.add_common_vars(host_groups, layout) output = StringIO.StringIO() self.config.write(output) return output.getvalue()
def test_docs_table_v2(): # Tables can be rectangles now! class Table(object): def __init__(self, height, width): self.height = height self.width = width def __repr__(self): return "<Table {self.height!r}x{self.width!r}>".format(self=self) from camel import Camel, CamelRegistry my_types = CamelRegistry() @my_types.dumper(Table, 'table', version=2) def _dump_table_v2(table): return { 'height': table.height, 'width': table.width, } @my_types.loader('table', version=2) def _load_table_v2(data, version): return Table(data["height"], data["width"]) @my_types.loader('table', version=1) def _load_table_v1(data, version): edge = data["size"]**0.5 return Table(edge, edge) table = Table(7, 10) assert Camel([my_types]).dump(table) == textwrap.dedent(""" !table;2 height: 7 width: 10 """).lstrip() @my_types.dumper(Table, 'table', version=1) def _dump_table_v1(table): return { # not really, but the best we can manage 'size': table.height * table.width, } camel = Camel([my_types]) camel.lock_version(Table, 1) assert camel.dump(Table(5, 7)) == "!table;1\nsize: 35\n"
def _sample_duck(): return Duck( random_route_from( Point( 53.095943, -2.469436, # a nice spot in the middle of Valley Brook srid=4326, ), experience=0)) if __name__ == '__main__': from sys import argv camel = Camel([registry]) try: with open('cli-duck.yaml', 'r') as f: duck = camel.load(f.read()) except FileNotFoundError: duck = _sample_duck() if duck.success is not None: print('your saved journey ended, starting a new one...') duck = Duck.make_successor() response = ' '.join(argv[1:]) or None advancement = duck.advance(response=response) print(duck.progress_summary(), end='\n\n')
def to_ordered_dict(filepath): data = yaml.load(open(filepath), Loader=yamlordereddictloader.Loader) data = Camel().dump(data["inventory_layout"]) return data
from duck import now, registry, _sample_duck from secrets import TWITTER DUCK_DIR = os.path.join( os.path.dirname(__file__), 'duck-storage', ) if not os.path.exists(DUCK_DIR): os.mkdir(DUCK_DIR) DUCK_IMAGE_LOCATION = os.path.join( os.path.dirname(__file__), 'duck.png', ) camel = Camel([registry]) auth = tweepy.OAuthHandler(TWITTER['consumer_key'], TWITTER['consumer_secret']) auth.set_access_token(TWITTER['access_token'], TWITTER['access_token_secret']) twitter = tweepy.API(auth) def get_duck(): duck_filenames = [ fn for fn in os.listdir(DUCK_DIR) if fn.endswith('.yaml') and not fn.startswith('.') ] if duck_filenames: latest_duck_filename = sorted(duck_filenames)[-1]
def dump(obj): return Camel([reg]).dump(obj)
def test_dieroll(): value = DieRoll(3, 6) camel = Camel([reg]) dumped = camel.dump(value) assert dumped == '!roll 3d6\n...\n' assert camel.load(dumped) == value
def save_yaml(data, path): with open(path, 'w') as f: f.write(Camel([standard_types_registry, camel_registry]).dump(data))
from camel import Camel from classtools import reify from django.contrib import messages from django.shortcuts import get_object_or_404, redirect from django.urls import reverse from django.views.generic import TemplateView, FormView from .forms import GameForm, JoinGameForm, ConfigureGameForm, SOURCE_SEP from .models import Room from ..game import reg, Game, Player from ..sources import SOURCES camel = Camel([reg]) class StartGameView(FormView): template_name = 'index.html' form_class = JoinGameForm def form_valid(self, form): if form.cleaned_data['room_code']: room = form.cleaned_data['room_code'] game_store = form.cleaned_data['room_code'].game_set.latest() else: room = Room.create_new() game_store = room.game_set.create() game = camel.load(game_store.state) or Game(players=[]) if not game.started:
from pytz import utc from sqlalchemy.orm.query import Query extension_content_types = { "json": "application/json", "yaml": "application/yaml", "rss": "application/rss+xml", "atom": "application/atom+xml", } JSONRenderer = JSON() JSONRenderer.add_adapter(date, lambda obj, request: obj.isoformat()) JSONRenderer.add_adapter(datetime, lambda obj, request: obj.isoformat()) camel_registry = CamelRegistry() camel = Camel([camel_registry]) class YAMLRenderer(object): def __init__(self, info): pass def __call__(self, value, system): system["request"].response.headers[ "Content-type"] = extension_content_types[ "yaml"] + "; charset=UTF-8" return camel.dump(value) class FeedRenderer(object): def __init__(self, info):
def dump(self): return Camel([camelRegistry]).dump(self)
def test_basic_roundtrip(value, expected_serialization): camel = Camel() dumped = camel.dump(value) assert dumped == expected_serialization assert camel.load(dumped) == value
def load(data): return Camel([reg]).load(data)
def load_yaml(path): with open(path, 'r') as f: data = Camel([camel_registry]).load(f.read()) return data
def save_yaml(data, path, lock_versions={}): with open(path, 'w') as f: c = Camel([standard_types_registry, camel_registry]) for klass, version in lock_versions.items(): c.lock_version(klass, version) f.write(c.dump(data))
def dump_raw(thing): raw = Camel(camel_registries).dump(thing) return raw
def load_raw(raw): thing = Camel(camel_registries).load(raw) return thing
def __init__(self, n): self.board = numpy.zeros(shape=(n, 5)) self.camel_list = [Camel(1), Camel(2), Camel(3), Camel(4), Camel(5)] self.winner = None
def load(cls, data, version=1): return Camel([camelRegistry]).load(data)