예제 #1
0
    def test_ready_narrator_01(self):
        Assembly.register(AssemblyTests.ForeignState)
        narrator = bluemonday78.story.build_narrator().set_state(
            AssemblyTests.ForeignState.hostile)
        self.assertTrue(hasattr(narrator, "memories"))
        self.assertIsInstance(narrator.memories, collections.deque)
        narrator.memories.extend(range(4))
        self.assertEqual(197801160800, narrator.state)
        self.assertEqual(4, len(narrator.memories))
        self.assertEqual(3, len(narrator._states))

        text = Assembly.dumps(narrator)
        clone = Assembly.loads(text)
        self.assertEqual(narrator.id, clone.id)
        self.assertTrue(hasattr(clone, "memories"))
        self.assertIsInstance(clone.memories, list)
        self.assertEqual(4, len(clone.memories))
        self.assertEqual(3, len(narrator._states))

        # Check state transfer
        self.assertEqual(197801160800, clone.state)
        clone.state = 0

        result = bluemonday78.story.build_narrator(id=None,
                                                   memories=clone.memories,
                                                   _states=clone._states)
        self.assertNotEqual(clone.id, result.id)
        self.assertTrue(hasattr(result, "memories"))
        self.assertIsInstance(result.memories, collections.deque)
        self.assertEqual(4, len(result.memories))
        self.assertEqual(0, result.state)
        self.assertEqual(3, len(result._states))
        self.assertEqual(AssemblyTests.ForeignState.hostile,
                         result.get_state(AssemblyTests.ForeignState))
예제 #2
0
def cgi_producer(args, stream=None):
    log_manager = LogManager()
    log = log_manager.get_logger("turberfield")
    log.info(args)
    try:
        handler = CGIHandler(Terminal(stream=stream),
                             None if args.db == "None" else args.db,
                             float(args.pause), float(args.dwell))
    except Exception as e:
        log.error(e)
        raise

    print("Content-type:text/event-stream", file=handler.terminal.stream)
    print(file=handler.terminal.stream)

    folders, references = resolve_objects(args)
    Assembly.register(*(i if isinstance(i, type) else type(i)
                        for i in references))
    log.info(folders)
    try:
        yield from rehearse(folders, references, handler, int(args.repeat),
                            int(args.roles), args.strict)
    except Exception as e:
        log.error(e)
        raise
    else:
        log.debug(references)
예제 #3
0
 def test_round_trip_assembly(self):
     Assembly.register(Player)
     player = Player(name="Mr Dick Turpin").set_state(12)
     text = Assembly.dumps(player)
     clone = Assembly.loads(text)
     self.assertEqual(player.id, clone.id)
     self.assertEqual(player.name, clone.name)
     self.assertEqual(player.state, clone.state)
예제 #4
0
 def test_uuid(self):
     # From Python 3.8 a UUID object has no __dict__
     self.assertNotIn(uuid.UUID, Assembly.encoding)
     self.assertNotIn(uuid.UUID, Assembly.decoding)
     Assembly.register(uuid.UUID)
     obj = uuid.uuid4()
     rv = Assembly.dumps(obj)
     self.assertIn(uuid.UUID, Assembly.encoding)
     self.assertIn("uuid.UUID", Assembly.decoding)
예제 #5
0
def presenter(args):
    handler = TerminalHandler(Terminal(), args.db, args.pause, args.dwell)
    folders, references = resolve_objects(args)
    Assembly.register(*(i if isinstance(i, type) else type(i)
                        for i in references))

    if args.log_level != logging.DEBUG:
        with handler.terminal.fullscreen():
            for folder in folders:
                yield from rehearse(folder, references, handler, args.repeat,
                                    args.roles, args.strict)
                input("Press return.")
    else:
        for folder in folders:
            yield from rehearse(folder, references, handler, args.repeat,
                                args.roles, args.strict)
예제 #6
0
def create_udp_node(loop, token, down, up):
    """
    Creates a node which uses UDP for inter-application messaging

    """
    assert loop.__class__.__name__.endswith("SelectorEventLoop")
 
    services = []
    types = Assembly.register(Policy)
    policies = Policy(poa=["udp"], role=[], routing=["application"])
    refs = match_policy(token, policies) or Flow.create(token, **policies._asdict())
    for ref in refs:
        obj = Flow.inspect(ref)
        key = next(k for k, v in policies._asdict().items() if ref.policy in v) 
        field = getattr(policies, key)
        field[field.index(ref.policy)] = obj
        try:
            services.append(obj.mechanism)
        except AttributeError:
            warnings.warn("Policy '{}' lacks a mechanism".format(ref.policy))

    udp = next(iter(policies.poa))
    Mix = type("UdpNode", tuple(services), {})
    transport, protocol = loop.run_until_complete(
        loop.create_datagram_endpoint(
            lambda:Mix(loop, token, types, down=down, up=up, **policies._asdict()),
            local_addr=(udp.addr, udp.port)
        )
    )
    return protocol
예제 #7
0
 def setUp(self):
     types = Assembly.register(Wheelbarrow,
                               Wheelbarrow.Brick,
                               Wheelbarrow.Bucket,
                               Wheelbarrow.Colour,
                               Wheelbarrow.Grip,
                               Wheelbarrow.Handle,
                               Wheelbarrow.Rim,
                               Wheelbarrow.Tyre,
                               Wheelbarrow.Wheel,
                               namespace="turberfield")
     self.assertEqual(9, len(types))
예제 #8
0
 def setUp(self):
     types = Assembly.register(
         Wheelbarrow,
         Wheelbarrow.Brick,
         Wheelbarrow.Bucket,
         Wheelbarrow.Colour,
         Wheelbarrow.Grip,
         Wheelbarrow.Handle,
         Wheelbarrow.Rim,
         Wheelbarrow.Tyre,
         Wheelbarrow.Wheel,
         namespace="turberfield"
     )
     self.assertEqual(9, len(types))
예제 #9
0
        if len(text
               ) not in formats and min(formats) < len(text) < max(formats):
            text = text + "0"
            mult = 10
        else:
            mult = 1
        try:
            format_string, span = formats[len(text)]
        except KeyError:
            return text, None
        else:
            return datetime.datetime.strptime(text, format_string), mult * span

    @property
    def clock(self):
        text = str(self.get_state(int))
        ts, span = self.parse_timespan(text)
        return ts

    @clock.setter
    def clock(self, hours=1):
        try:
            td = datetime.timedelta(hours=hours)
            ts = self.clock + td
            self.set_state(int(ts.strftime(self.state_format)))
        finally:
            return self.clock


Assembly.register(Look, Mode, Trade, Spot, Character, Location, Narrator)
예제 #10
0
class Court(Exterior):
    pass


class Sanctum(Interior):
    pass


class Pit(Exterior):
    pass


class Workings(Interior):
    pass


class Forest(Interior):
    pass


class Heath(Exterior):
    pass


class Woodland(Exterior):
    pass


Assembly.register(Spot)
예제 #11
0
    Swarfega and blue roll. She has a limited capacity for storing
    recovered fuel; she will consider selling petrol or diesel to
    you if she trusts you.

    """
    pass

class MarketStall(Trader):
    """
    {proprietor.name} has a stall on the market. He'll buy anything
    but only at a rock-bottom price.

    """
    pass

class Antiques(Trader):
    """
    {proprietor.name} runs an antique shop. She's always looking
    for fabrics which she cuts up and sells as rare designs. She'll
    also buy picture frames if they're cheap and contemporary.

    """
    pass

Assembly.register(
    Name,
    Ownership, Presence, Vocabulary,
    Character, Commodity, Location, Plank, Table,
    FormB107, Keys, Location, Prisoner, PrisonOfficer, PrisonVisitor,
)
예제 #12
0
# encoding: UTF-8

__doc__ = """
This module was generated by turberfield.ops.svgforger:

fontforge /home/boss/src/turberfield-ops/turberfield/ops/svgforger.py --name=addisonarches \
--prefix=diorama --output=~/src/addisonarches/addisonarches/web/static \
/home/boss/src/addisonarches/assets/formb107.svg \
/home/boss/src/addisonarches/assets/keys.svg \
/home/boss/src/addisonarches/assets/prisoner.svg \
/home/boss/src/addisonarches/assets/prisonofficer.svg \
/home/boss/src/addisonarches/assets/prisonvisitor.svg

"""

from collections import namedtuple
from turberfield.utils.assembly import Assembly

Icon = namedtuple("Icon", ["font", "prefix", "name", "ordinal"])

icons = [
    Icon("addisonarches", "diorama", "formb107", 350),
    Icon("addisonarches", "diorama", "keys", 351),
    Icon("addisonarches", "diorama", "prisoner", 352),
    Icon("addisonarches", "diorama", "prisonofficer", 353),
    Icon("addisonarches", "diorama", "prisonvisitor", 354),
]

Assembly.register(Icon)

예제 #13
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with turberfield.  If not, see <http://www.gnu.org/licenses/>.

from collections import namedtuple

from turberfield.utils.assembly import Assembly

Address = namedtuple(
    "Address",
    ["namespace", "user", "service", "application"]
)
Address.__doc__ = """`{}`

A semantically hierarchical address for distributed networking.

    namespace
        Specifies the domain within which the address names are valid.
    user
        A unique name of trust within the network.
    service
        Identifies a currently operating instantiation of the network.
    application
        The name of the node endpoint.

""".format(Address.__doc__)

Assembly.register(Address)
예제 #14
0
    slab = 24e-3
    case = 16e-3
    bundle = 8e-3
    tray = 4e-3
    carton = 2e-3
    brick = 1.5e-3
    bottle = 1e-3
    litre = 1e-3
    pack = 5e-4
    zero = 0

    @classmethod
    def factory(cls, name=None, **kwargs):
        return cls[name]


class Inventory:

    def __init__(self, capacity):
        self.capacity = capacity
        self.contents = Counter()

    @property
    def constraint(self) -> float:
        return sum(
            getattr(c.volume, "value", c.volume) * n
            for c, n in self.contents.items()
        ) / self.capacity

Assembly.register(Volume)
예제 #15
0
def cgi_consumer(args):
    folders, references = resolve_objects(args)
    Assembly.register(*(i if isinstance(i, type) else type(i)
                        for i in references))

    resources = list(
        rehearse(folders,
                 references,
                 yield_resources,
                 repeat=0,
                 roles=args.roles,
                 strict=args.strict))
    links = "\n".join('<link ref="prefetch" href="/{0}">'.format(i)
                      for i in resources)
    params = [(k, v) for k, v in vars(args).items()
              if k not in ("folder", "session")]
    params.append(("session", uuid.uuid4().hex))
    params.extend([("folder", i) for i in args.folder])
    opts = urllib.parse.urlencode(params)
    url = "http://localhost:{0}/{1}/turberfield-rehearse?{2}".format(
        args.port, args.locn, opts)
    rv = textwrap.dedent("""
        Content-type:text/html

        <!doctype html>
        <html lang="en">
        <head>
        <meta charset="utf-8" />
        <title>Rehearsal</title>
        {links}
        <style>
        #line {{
            font-family: "monospace";
        }}
        #line .persona::after {{
            content: ": ";
        }}
        #event {{
            font-style: italic;
        }}
        </style>
        </head>
        <body class="loading">
        <h1>...</h1>
        <blockquote id="line">
        <header class="persona"></header>
        <p class="data"></p>
        </blockquote>
        <audio id="cue"></audio>
        <span id="event"></span>
        <script>
            if (!!window.EventSource) {{
                var source = new EventSource("{url}");
            }} else {{
                alert("Your browser does not support Server-Sent Events.");
            }}

            source.addEventListener("audio", function(e) {{
                console.log(e);
                var audio = document.getElementById("cue");
                audio.setAttribute("src", e.data);
                audio.currentTime = 0;
                audio.play();
            }}, false);

            source.addEventListener("line", function(e) {{
                console.log(e);
                var event = document.getElementById("event");
                event.innerHTML = "";
                var obj = JSON.parse(e.data);
                var quote = document.getElementById("line");
                var speaker = quote.getElementsByClassName("persona")[0];
                var line = quote.getElementsByClassName("data")[0];

                speaker.innerHTML = obj.persona.name.firstname;
                speaker.innerHTML += " ";
                speaker.innerHTML += obj.persona.name.surname;
                line.innerHTML = obj.html;

            }}, false);

            source.addEventListener("memory", function(e) {{
                var obj = JSON.parse(e.data);
                var event = document.getElementById("event");
                event.innerHTML = obj.html;
            }}, false);

            source.addEventListener("property", function(e) {{
                var obj = JSON.parse(e.data);
                var event = document.getElementById("event");
                event.innerHTML = "<";
                event.innerHTML += obj.object._name;
                event.innerHTML += ">.";
                event.innerHTML += obj.attr;
                event.innerHTML += " = ";
                event.innerHTML += obj.val.name || obj.val;
            }}, false);

            source.addEventListener("open", function(e) {{
                console.log("Connection was opened.");
            }}, false);

            source.addEventListener("error", function(e) {{
                console.log("Error: connection lost.");
            }}, false);

        </script>
        </body>
        </html>
    """).format(links=links, url=url).lstrip()
    return rv
예제 #16
0
        elif isinstance(obj, (Ask, Bid)):
            series = self[commodity]
            series.append(obj)
        else:
            raise NotImplementedError

        return self.estimate(series)

    def consider(self, commodity, offer:set([Ask, Bid]), constraint=1.0):
        estimate = self.estimate(self[commodity])
        if isinstance(offer, Ask):
            if offer.value < estimate.value or random.random() >= constraint:
                return self.commit(commodity, offer)
            else:
                return estimate
        elif isinstance(offer, Bid):
            if offer.value > estimate.value or random.random() <= constraint:
                return self.commit(commodity, offer)
            else:
                return estimate
        else:
            raise NotImplementedError

    def setdefault(self, key, default=None):
        raise NotImplementedError

    def update(self, other):
        raise NotImplementedError

Assembly.register(Ask, Bid, Note, Valuation)
예제 #17
0
    def nickname(self):
        return random.choice(self.name.nicknames)


class Stateful:

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._states = {}

    @property
    def state(self):
        return self.get_state()

    @state.setter
    def state(self, value):
        return self.set_state(value)

    def set_state(self, *args):
        for value in args:
            self._states[type(value).__name__] = value
        return self

    def get_state(self, typ=int, default=0):
        return self._states.get(typ.__name__, default)

class Player(Persona, Stateful):
    pass

Assembly.register(Name, type(uuid.uuid4()))
예제 #18
0
 def setUpClass(cls):
     Assembly.register(
         Belt, Glyph, Length, Pellets, Shell, String, Wampum
     )
예제 #19
0
    options = Game.options(Game.Player(user, name), parent=parent)
    game = Game(
        Game.Player(user, name),
        addisonarches.scenario.easy.businesses[:],
        clock,
        token,
        up,
        down=down,
        loop=loop,
        **options
    ).load()
    return (game, clock, down, up)

def init_game(game, clock, down, up, loop=None):
    loop.create_task(clock(loop=loop))
    loop.create_task(game(loop=loop))

    progress = Persistent.recent_slot(game._services["progress.rson"].path)
    return (progress, down, up)

def create(parent, user, name, token, down=None, up=None, loop=None):
    return init_game(
        *create_game(parent, user, name, token, down, up, loop=loop),
        loop=loop
    )

Assembly.register(
    Clock.Tick, Game.Avatar, Game.Drama, Game.Item, Game.Tally, Game.Via,
    Model.Line, Player
)
예제 #20
0
    def cast(self, mapping):
        """Allocate the scene script a cast of personae for each of its entities.

        :param mapping: A dictionary of {Entity, Persona}
        :return: The SceneScript object.

        """
        # See 'citation' method in
        # http://docutils.sourceforge.net/docutils/parsers/rst/states.py
        for c, p in mapping.items():
            self.doc.note_citation(c)
            self.doc.note_explicit_target(c, c)
            c.persona = p
            self.log.debug(
                "{0} to be played by {1}".format(c["names"][0].capitalize(),
                                                 p), {"path": self.fP})
        return self

    def run(self):
        """Parse the script file.

        :rtype: :py:class:`~turberfield.dialogue.model.Model`
        """
        model = Model(self.fP, self.doc)
        self.doc.walkabout(model)
        return model


Assembly.register(Model.Audio, Model.Line, Model.Memory, Model.Property,
                  Model.Still, Model.Video)
예제 #21
0
                    valuation = self.book.consider(
                        type(focus), offer, constraint=0
                    )
                    yield Trader.Patter(self.proprietor, (
                        "I can go to "
                        "{0.currency}{0.value:.0f}.".format(valuation)
                    ))
                else:
                    yield Trader.Patter(self.proprietor, (
                        "I'll agree on "
                        "{0.currency}{0.value}.".format(offer)
                    ))
                    asset = Asset(focus, None, ts)
                    picks = game.businesses[0].retrieve(asset)
                    quantity = sum(i[1] for i in picks)
                    price = quantity * offer.value
                    self.store(
                        Asset(focus, quantity, ts)
                    )
                    self.tally -= price
                    game.businesses[0].tally += price
                    game.drama = None
            except (TypeError, NotImplementedError) as e:
                # No offer yet
                yield Trader.Patter(
                    self.proprietor,
                    "How much are you asking for a {0.label}?".format(focus)
                )

Assembly.register(Buying, Selling, Trader.Patter)
예제 #22
0
Alert = namedtuple("Alert", ["ts", "text"])
Scalar = namedtuple("Scalar", ["name", "unit", "value", "regex", "tip"])

Message = namedtuple("Message", ["header", "payload"])
Message.__doc__ = """`{}`

An Message object holds both protocol control information (PCI) and
application data.

    header
        PCI data necessary for the delivery of the message.
    payload
        Client data destined for the application endpoint.
""".format(Message.__doc__)

Assembly.register(Alert, Header, Message, Scalar)

def parcel(token, *args, dst=None, via=None, hMax=3):
    """
    :param token: A DIF token. Just now the function
                  `turberfield.ipc.fsdb.token`_ is the source of these.
    :param args: Application objects to send in the message.
    :param dst: An :py:class:`Address <turberfield.ipc.types.Address>` for the destination.
                If `None`, will be set to the source address (ie: a loopback message).
    :param via: An :py:class:`Address <turberfield.ipc.types.Address>` to
                pass the message on to. If `None`, the most direct route is selected.
    :param hMax: The maximum number of node hops permitted for this message.
    :rtype: Message


    """
예제 #23
0
from turberfield.dialogue.types import Stateful
from turberfield.utils.assembly import Assembly

__doc__ = """
A simple drama for demonstration.

"""


class Animal(Stateful, Persona):
    pass

class Tool(Stateful, Persona):
    pass

def ensemble():
    return [
        Animal(name="Itchy").set_state(1),
        Animal(name="Scratchy").set_state(1),
        Tool(name="Ol' Rusty Chopper").set_state(1),
    ]

references = ensemble()

folder = SceneScript.Folder(
    "turberfield.dialogue.sequences.battle",
    __doc__, None, ["combat.rst"], None
)

Assembly.register(Animal, Tool)
예제 #24
0
# Turberfield is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with turberfield.  If not, see <http://www.gnu.org/licenses/>.

from collections import namedtuple

from turberfield.utils.assembly import Assembly

Address = namedtuple("Address",
                     ["namespace", "user", "service", "application"])
Address.__doc__ = """`{}`

A semantically hierarchical address for distributed networking.

    namespace
        Specifies the domain within which the address names are valid.
    user
        A unique name of trust within the network.
    service
        Identifies a currently operating instantiation of the network.
    application
        The name of the node endpoint.

""".format(Address.__doc__)

Assembly.register(Address)
예제 #25
0
 def test_enums_can_be_assembled(self):
     self.assertTrue(Assembly.register(Map.Arriving))
     rv = Assembly.dumps(Map.Arriving.car_park)
     self.assertEqual(Map.Arriving.car_park, Assembly.loads(rv), rv)