예제 #1
0
class Scanner():
    def __init__(self, direction, puzzle, wordsToFind):
        self.observable = Observable()
        self.direction = direction
        self.puzzle = puzzle
        self.puzzleRows = len(puzzle)
        self.puzzleColumns = len(puzzle[0])
        self.wordsToFind = wordsToFind

    def scan_for_words(self):
        for row, letters in enumerate(self.puzzle):
            for column, letter in enumerate(letters):
                for word in self.__get_first_letter_matches(letter):
                    if self.__enough_room_for_word(len(word), row, column):
                        foundWordCoordinates = self.__search_for_word(
                            word, row, column)
                        if len(foundWordCoordinates) != 0:
                            self.observable.update_observers(
                                foundWordCoordinates)

    def register(self, observer):
        self.observable.register(observer)

    def __enough_room_for_word(self, lengthOfWord, row, column):
        if row + lengthOfWord * self.direction[1] > self.puzzleColumns:
            return False
        elif column + lengthOfWord * self.direction[0] > self.puzzleRows:
            return False
        else:
            return True

    def __get_first_letter_matches(self, letter):
        matches = []
        for word in self.wordsToFind:
            if word[0] == letter:
                matches.append(word)
        return matches

    def __search_for_word(self, word, row, column):
        wordCoordinates = [(column, row)]

        for position, letter in enumerate(word[1:]):
            rowOffset = (position + 1) * self.direction[1]
            columnOffset = (position + 1) * self.direction[0]
            if not self.puzzle[row + rowOffset][column +
                                                columnOffset] == letter:
                return []
            else:
                wordCoordinates.append(
                    (column + columnOffset, row + rowOffset))
        return wordCoordinates
예제 #2
0
from observable import Observable
from observer import Observer


class AmericanStockMarket(Observer):
    def update(self, *args, **kwargs):
        print("American stock market recevied: {0}\n{1}".format(args, kwargs))


class EuropeanStockMarket(Observer):
    def update(self, *args, **kwargs):
        print("European stock market recevied: {0}\n{1}".format(args, kwargs))


if __name__ == '__main__':
    observable = Observable()

    american_observer = AmericanStockMarket()
    observable.register(american_observer)

    european_observer = EuropeanStockMarket()
    observable.register(european_observer)

    observable.update_observers('Market Rally', something='hello world')
예제 #3
0
파일: kb.py 프로젝트: gomjellie/pureEv3Py
from keyboard import KeyBoard
from observable import Observable
from observer import Observer
from actor import Actor

if __name__ == '__main__':
    observable = Observable()
    keyBoard = KeyBoard()
    actor = Actor()
    observable.register(actor)
    while 1:
        observable.update_observers(c=keyBoard.get_ch())
#!/usr/bin/python

# imports for observer pattern and scrapping stdout
from observable import Observable
from observer import Observer
import os

# imports for type-observer-view
from testobserverview import TestObserverView

import subprocess, time, os, sys
cmd = ["sudo", "tcpdump", "-c", "5"]

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

observable = Observable()

test_observer = TestObserverView()
observable.register(test_observer)

for line in iter(p.stdout.readline, b''):
    observable.update_observers(line.rstrip())

print("program ended")
예제 #5
0
class BasePool(object):
    def __init__(self, N, food_size):
        self.reaction_computed = Observable()
        self.step_computed = Observable()
        self.generation_computed = Observable()
        self.expressions = Multiset(N)
        self.tmp_removed_expressions = []
        self.food_size = food_size

    def register_step_observer(self, obs):
        self.step_computed.register(obs.on_step_computed)

    def register_reaction_observer(self, obs):
        self.reaction_computed.register(obs.on_reaction_computed)

    def deregister_observers(self):
        self.reaction_computed.deregister_all()
        self.step_computed.deregister_all()

    def pop_reactive(self):
        assert len(self.expressions) > 0
        t = self.expressions.sample()
        self.tmp_remove(t)
        return t

    def rollback(self, t):
        self.tmp_removed_expressions.remove(t)
        self.append(t)

    def get_total_size(self):
        return sum(len(expr) for expr in self.expressions) + \
                sum(len(expr) for expr in self.tmp_removed_expressions)

    def __len__(self):
        return len(self.expressions) + len(self.tmp_removed_expressions)

    def __iter__(self):
        return iter(self.expressions)

    def unique(self):
        return self.expressions.unique()

    def __contains__(self, t):
        return t in self.expressions or self.can_make(t)

    def load(self, fn):
        raise NotImplementedError()

    def append(self, t):
        self.expressions.add(t)

    def tmp_remove(self, t):
        self.tmp_removed_expressions.append(t)
        self.expressions.remove(t)

    def remove(self, t):
        if t in self.tmp_removed_expressions:
            self.tmp_removed_expressions.remove(t)
            return True
        else:
            if t in self.expressions:
                self.expressions.remove(t)
                return True
            else:
                return False
        #if t == Expression.parse('SII'):
        #    print('food# ' ,self.get_multiplicity(t))

    def remove_all(self, ts):
        for t in ts:
            if not self.remove(t):
                return False
        return True

    def apply_reaction(self, reaction):
        if self.has_or_make_reactives(reaction):
            for r in reaction.reactives:
                self.remove(r)
            for p in reaction.products:
                self.append(p)
            self.reaction_computed(self, reaction)
            return True
        else:
            return False

    def has_or_make_reactives(self, reaction):
        reactives = reaction.reactives
        missing = self.count_missing(reactives)
        if any(r not in self and r not in self.tmp_removed_expressions
               for r in reactives):
            assert missing[r] > 0
        #if missing:
        #    print(reaction, {str(k): v for k,v in missing.items()})
        for compound, count in missing.items():
            if count > 0:
                made = self.make(compound, count)
                #NOTE: a compound can be made before noticing than another
                # cannot be made, but it should never happen with these
                # binary reactions.
                if not made:
                    return False
        return True

    def count_missing(self, reactives):
        missing = Counter(self.expressions.count_missing(reactives))
        in_tmp = Counter(self.tmp_removed_expressions)
        return Counter({k: v - in_tmp[k] for k, v in missing.items()})

    def make(self, compound, count):
        for i in range(count):
            if not self.can_make(compound):
                return False
            if self.remove_all(compound.atoms()):
                self.append(compound)
        return True

    def can_make(self, ts):
        if self.food_size is None or len(ts) > self.food_size:
            return False
        return self.expressions.has_all(ts.atoms())

    def get_multiplicity(self, t):
        return self.expressions[t] - self.tmp_removed_expressions.count(t)

    def __getitem__(self, t):
        return self.get_multiplicity(t)

    def __str__(self):
        pool_strs = []
        for k in sorted(set(self.expressions),
                        key=lambda k: self.expressions[k]):
            pool_strs.append(f"{k} {self.expressions[k]}")
        return "\n".join(pool_strs)

    def serializable(self):
        return {x.serializable(): self[x] for x in self.unique()}

    def evolve(self, num_reactions, timeout_time=1):
        for i in range(num_reactions):
            #with timeout(timeout_time):
            self.step()
            self.step_computed(self, i)

    def evolve_generations(self, num_generations):
        tick = 0
        for i in range(num_generations):
            for j in range(len(self)):
                self.step()
                self.step_computed(self, tick)
                tick += 1
            self.generation_computed(i)
예제 #6
0
class observable_test(unittest.TestCase):
    def setUp(self):
        self.observable = Observable()

        self.observer1 = AnObserver()
        self.observer2 = AnObserver()
        self.observer3 = AnObserver()

    def test_remove_all(self):
        self.observable.register(self.observer1)
        self.observable.register(self.observer2)
        self.observable.register(self.observer3)

        self.observable.unregister_all()

        # Should be zero registered
        self.assertEqual(len(self.observable.observers), 0)

    def test_register(self):
        self.observable.register(self.observer1)
        self.observable.register(self.observer2)
        self.observable.register(self.observer3)

        # Should be three registered
        self.assertEqual(len(self.observable.observers), 3)
        self.observable.unregister_all()

    def test_unregister(self):
        self.observable.register(self.observer1)
        self.observable.register(self.observer2)
        self.observable.register(self.observer3)

        self.observable.unregister(self.observer2)
        self.observable.unregister(self.observer3)

        # Should be 1 registered
        self.assertEqual(len(self.observable.observers), 1)
        self.observable.unregister_all()

    def test_update_observers(self):
        self.observable.register(self.observer1)

        self.observable.update_observers('abc', msg='123')
        self.assertEqual(self.observer1.args[0], 'abc')
        self.assertEqual(self.observer1.kwargs['msg'], '123')
        self.observable.unregister_all()
예제 #7
0
from observer import Subscriber1, Subscriber2
from observable import Observable

# test code

sports_magazine = Observable()
lofty = Subscriber1()
sports_magazine.register(lofty)
mier = Subscriber2()
sports_magazine.register(mier)
sports_magazine.update("Important update",
                       msg="Micheal Jordan will join Lakers team")
sports_magazine.unregister(mier)
sports_magazine.update("Latest update",
                       msg="Mier unregistered to sports magazine")
예제 #8
0
파일: app.py 프로젝트: xe1gyq/EekMex
from observable import Observable
from observer import Observer
 
 
class AmericanStockMarket(Observer):
    def update(self, *args, **kwargs):
        print("American stock market received: {0}\n{1}".format(args, 
kwargs))
 
 
class EuropeanStockMarket(Observer):
    def update(self, *args, **kwargs):
        print("European stock market received: {0}\n{1}".format(args, 
kwargs))
 
 
if __name__ == "__main__":
    observable = Observable()
 
    american_observer = AmericanStockMarket()
    observable.register(american_observer)
 
    european_observer = EuropeanStockMarket()
    observable.register(european_observer)
 
    observable.update_observers('Market Rally', something='Hello World')

class observerable_test(unittest.TestCase):
 
    def setUp(self):
        self.observable = Observable()
 
        self.observer1 = AnObserver()
        self.observer2 = AnObserver()
        self.observer3 = AnObserver()
 
    def test_remove_all(self):
        self.observable.register(self.observer1)
        self.observable.register(self.observer2)
        self.observable.register(self.observer3)
 
        self.observable.unregister_all()
 
        # Should be zero registered
        self.assertEqual(len(self.observable.observers), 0)
 
    def test_register(self):
        self.observable.register(self.observer1)
        self.observable.register(self.observer2)
        self.observable.register(self.observer3)
 
        # Should be three registered
        self.assertEqual(len(self.observable.observers), 3)
        self.observable.unregister_all()
 
    def test_unregister(self):
        self.observable.register(self.observer1)
        self.observable.register(self.observer2)
        self.observable.register(self.observer3)
 
        self.observable.unregister(self.observer2)
        self.observable.unregister(self.observer3)
 
        # Should be one registered
        self.assertEqual(len(self.observable.observers), 1)
        self.observable.unregister_all()
 
    '''   
class observerable_test(unittest.TestCase):
 
    def setUp(self):
        self.observable = Observable()
 
        self.observer1 = AnObserver()
        self.observer2 = AnObserver()
        self.observer3 = AnObserver()
 
    def test_remove_all(self):
        self.observable.register(self.observer1)
        self.observable.register(self.observer2)
        self.observable.register(self.observer3)
 
        self.observable.unregister_all()
 
        # Should be zero registered
        self.assertEqual(len(self.observable.observers), 0)
 
    def test_register(self):
        self.observable.register(self.observer1)
        self.observable.register(self.observer2)
        self.observable.register(self.observer3)
 
        # Should be three registered
        self.assertEqual(len(self.observable.observers), 3)
        self.observable.unregister_all()
 
    def test_unregister(self):
        self.observable.register(self.observer1)
        self.observable.register(self.observer2)
        self.observable.register(self.observer3)
 
        self.observable.unregister(self.observer2)
        self.observable.unregister(self.observer3)
 
        # Should be one registered
        self.assertEqual(len(self.observable.observers), 1)
        self.observable.unregister_all()
 
    def test_update_observers(self):
        self.observable.register(self.observer1)
 
        self.observable.update_observers('abc', msg='123')
        self.assertEqual(self.observer1.args[0], 'abc')
        self.assertEqual(self.observer1.kwargs['msg'], '123')
        self.observable.unregister_all()
# Example of how to use the Observable and Observer abstract classes

from observable import Observable
from observer import Observer


class AmericanStockMarket(Observer):
    def update(self, *args, **kwargs):
        print("American stock market received: {0}\n{1}".format(args, kwargs))


class JapaneseStockMarket(Observer):
    def update(self, *args, **kwargs):
        print("Japanese stock market received: {0}\n{1}".format(args, kwargs))


if __name__ == "__main__":
    observable = Observable()

    american_observer = AmericanStockMarket()
    observable.register(american_observer)

    japanese_observer = JapaneseStockMarket()
    observable.register(japanese_observer)

    observable.update_observers('Market Rally', something='hello Scott')
예제 #12
0
from keyboard import KeyBoard
from observable import Observable
from observer import Observer
from input_handler import InputHandler#Actor
from view import View
import curses

if __name__ == '__main__':
    observable = Observable()
    screen = curses.initscr()
    curses.noecho()
    curses.cbreak()
    keyBoard = KeyBoard(screen)
    input_handler = InputHandler()
    view = View(screen)
    observable.register(input_handler)
    observable.register(view)
    while 1:
    	try:
    	    observable.update_observers(c=keyBoard.get_ch())
    	except KeyboardInterrupt:
    	    curses.endwin()
    	    exit()