コード例 #1
0
class WaiterTestCase(unittest.TestCase):
    def setUp(self) -> None:
        self.waiter1 = Waiter("Harry Potter", 150)
        self.waiter1.customers_served = 42

        self.barista1 = Barista("Hermione Granger", 160)

    def test_init(self):
        w = Waiter("Ron Weasley", 149)
        self.assertEqual(w.full_name, "Ron Weasley")
        self.assertEqual(w.salary, 149)
        self.assertEqual(w.customers_served, 0)

        self.assertEqual(self.waiter1.full_name, "Harry Potter")
        self.assertEqual(self.waiter1.salary, 150)
        self.assertEqual(self.waiter1.customers_served, 42)

    def test_serve(self):
        # for Ron Weasley
        w = Waiter("Ron Weasley", 149)
        w.serve(54, self.barista1)
        self.assertEqual(w.customers_served, 54)

        # for Harry Potter (has already served 42 and serves +31)
        self.waiter1.serve(31, self.barista1)
        self.assertEqual(self.waiter1.customers_served, 73)

        # for Hermione Granger [54 (from Ron) + 31 (from Harry, the 42 from before don't count as they aren't prepared by barista1)
        self.assertEqual(self.barista1.customers_served, 85)
        print(
            f"the Barista {self.barista1.full_name} served {self.barista1.customers_served} customers at the end of the test day"
        )
コード例 #2
0
ファイル: douyin.py プロジェクト: xrr8417403/douyin-1
 def __init__(self,
              proxy_api=PROXY_API,
              token_file=TOKEN_FILE,
              token=API_TOKEN):
     self.token = token
     self.proxy_api = proxy_api
     self.token_file = token_file
     self.waiter = Waiter()
コード例 #3
0
    def start(self, on_step=lambda min_left, sec_left: None, on_end=lambda completed: None):
        def step(time_left):
            left = int(time_left)
            on_step(left / self.minute, left % self.minute)

        waiter = Waiter(self.length, self.second, step, on_end)
        waiter.start()
        step(self.length)
        return waiter
コード例 #4
0
    def test_serve(self):
        # for Ron Weasley
        w = Waiter("Ron Weasley", 149)
        w.serve(54, self.barista1)
        self.assertEqual(w.customers_served, 54)

        # for Harry Potter (has already served 42 and serves +31)
        self.waiter1.serve(31, self.barista1)
        self.assertEqual(self.waiter1.customers_served, 73)

        # for Hermione Granger [54 (from Ron) + 31 (from Harry, the 42 from before don't count as they aren't prepared by barista1)
        self.assertEqual(self.barista1.customers_served, 85)
        print(
            f"the Barista {self.barista1.full_name} served {self.barista1.customers_served} customers at the end of the test day"
        )
コード例 #5
0
ファイル: runtests.py プロジェクト: Ricyteach/mypy
 def __init__(self, *, whitelist: List[str], blacklist: List[str],
         lf: bool, ff: bool,
         arglist: List[str], pyt_arglist: List[str],
         verbosity: int, parallel_limit: int,
         xfail: List[str], coverage: bool) -> None:
     self.whitelist = whitelist
     self.blacklist = blacklist
     self.arglist = arglist
     self.pyt_arglist = pyt_arglist
     self.verbosity = verbosity
     self.waiter = Waiter(verbosity=verbosity, limit=parallel_limit, xfail=xfail, lf=lf, ff=ff)
     self.versions = get_versions()
     self.cwd = os.getcwd()
     self.env = dict(os.environ)
     self.coverage = coverage
コード例 #6
0
 def test_notification(self):
     factory = BurritoFactory(discount = 0)
     order = factory.order_dish()
     waiter = Waiter()
     order.attach(waiter)
     with patch.object(waiter, "update") as mock_update:
         order.prepare()
         self.assertEqual(mock_update.call_count, 1)
コード例 #7
0
    def testWaiterOK(self):
        iterations = "27 9"
        numbers = "27 17 60 38 67 90 4 43 74 17 25 16 26 51 78 23 58 63 84 41 3 73 12 50 66 60 33 57 27 35 73 59 34 69 \
        31 88 19 12 70 46 18 32 75 89 63 28 77 47 20 44 47 17 32 2 88 5 30 66 83 77 2 51 80 34 37 68 77 90 80 64 41 35 \
        86 70 86 17 39 55 22 42 76 39 7 51 56"
        waiter = Waiter(iterations, numbers)
        piles = waiter.stackPiles()

        expectedResult = "60 38 90 4 74 16 26 78 58 84 12 50 66 60 34 88 12 70 46 18 32 28 20 44 32 2 88 30 66 2 80 34 \
        68 90 80 64 86 70 86 22 42 76 56 51 39 39 51 63 75 69 27 57 33 3 63 51 27 25 35 5 35 55 7 77 77 77 17 17 17 17 \
        19 23 67 43 41 73 73 59 31 89 47 47 83 37 41"
        platesResult = list(map(int, expectedResult.split()))   # Convert the expected result in a list of integers
        counterPlate = 0    # Counter for iterate the expected values list
        for pile in piles:
            for plate in pile:
                self.assertEqual(plate, platesResult[counterPlate])
                counterPlate += 1
コード例 #8
0
 def test_if_observer_is_attachable_and_detachable(self):
     factory = BurritoFactory(discount = 0)
     order = factory.order_dish()
     waiter = Waiter()
     order.attach(waiter)
     self.assertEqual(isinstance(order._observers[0], Waiter), True)
     self.assertEqual(len(order._observers), 1)
     order.detach(waiter)
     self.assertEqual(len(order._observers), 0)
コード例 #9
0
    def test_init(self):
        w = Waiter("Ron Weasley", 149)
        self.assertEqual(w.full_name, "Ron Weasley")
        self.assertEqual(w.salary, 149)
        self.assertEqual(w.customers_served, 0)

        self.assertEqual(self.waiter1.full_name, "Harry Potter")
        self.assertEqual(self.waiter1.salary, 150)
        self.assertEqual(self.waiter1.customers_served, 42)
コード例 #10
0
    def wait_page_load(self, timeout=TIMEOUT):

        def _wait_page_load():
            return self.is_document_ready

        if Waiter.poll(timeout, _wait_page_load):
            return
        else:
            raise TimeoutException(
                "Page wasn't load after %s seconds." % timeout)
コード例 #11
0
def main():
    all_menus = Menu('All', 'it is all menu')
    lunch_menu = Menu('Lunch', 'it is lunch menu')
    dinner_menu = Menu('Dinner', 'it is dinner menu')
    drink_menu = Menu('Drink', 'it is drink menu')
    dessert_menu = Menu('Dessert', 'it is dessert menu')

    all_menus.add_child(lunch_menu)
    all_menus.add_child(dinner_menu)
    lunch_menu.add_child(MenuItem('beef', '240', 'pan-fried steak'))
    lunch_menu.add_child(drink_menu)
    drink_menu.add_child(MenuItem('milk tea', '50', 'milk tea without sugar'))
    dinner_menu.add_child(MenuItem('salmon', '340', 'pan-fried salmon'))
    dinner_menu.add_child(MenuItem('whole wheat bread', '50',
                                   'for vegetarian'))
    dinner_menu.add_child(dessert_menu)
    dessert_menu.add_child(MenuItem('Waffle', '100', 'delicious'))
    waiter = Waiter(all_menus)
    waiter.show_menu()
コード例 #12
0
    def find_element(self, id_selector, timeout=TIMEOUT):

        def _is_element_present():
            return self.web_driver.find_element_by_id(id_selector)

        element = Waiter.poll(timeout, _is_element_present)
        if element:
            return element

        raise TimeoutException('Element "%s" was present after %s seconds.' %
                               (id_selector, timeout))
コード例 #13
0
    def order_dish(self):
        self.store = StoreProxy().create_store()

        if self.store:
            self.waiter = Waiter()
            chosen_dish_kind = self.store.choose_dish_kind()
            self.factory = self.store.create_factory(chosen_dish_kind)

            if self.factory:
                order = self.factory.order_dish()

                if order:
                    order.id = len(self.store.orders_list) + 1
                    order.attach(self.waiter)
                    self.store.orders_list.append(order)
                    self.store.orders_list[-1].print_info()
                    self.store.orders_list[-1].prepare()
コード例 #14
0
ファイル: main.py プロジェクト: vmirisas/Python_Lessons
def main():
    seed(datetime.now())

    o = Owner("owner", 100000)
    w1 = Waiter("waiter1", 200000)
    w2 = Waiter("waiter2", 200000)
    b = Barista("barista", 300000)

    waiters = [o, w1, w2]
    baristas = [o, b]

    for i in range(10):
        waiters[randrange(len(waiters))].serve(randrange(1, 3 + 1), baristas[randrange(len(baristas))])

    print("")
    o.report()
    w1.report()
    w2.report()
    b.report()
コード例 #15
0
def _load():
    global wa, q, data, w
    try:
        with open(FN_WORKSPACE) as fp:
            _workspace = dill.loads(fp.read())
            # To store any user data
            data = _workspace['data']
            wa = _workspace['wa']
            q = _workspace['q']
            q.connect()
            w = _workspace['w']
    except IOError:
        data = {}
        wa = WeiboAutomator()
        q = Queue('message.db')
        q.connect()
        w_timeline = Waiter(200, wa.home_timeline, (), {
            'count': 100,
            'callback': q.input
        })
        w = [w_timeline]
コード例 #16
0
ファイル: ques.py プロジェクト: RoyQuitt/Lineder
 def get_my_que(user_address):
     user_id = MyUser.get_id_by_email(user_address)
     db = get_db()
     que_ids = db.execute("SELECT * FROM ques WHERE callee_id = ?",
                          (user_id, )).fetchall()
     # print(que_ids)
     que: list[Waiter] = []
     for waiter in que_ids:
         c_id = waiter[1]
         c_user = MyUser.get(c_id)
         c_name = c_user.name
         c_address = c_user.email
         c_phone = c_user.phone
         c_waiter = Waiter(email=c_address,
                           name=c_name,
                           phone=c_phone,
                           place=waiter[2])
         que.append(c_waiter)
     # print("que:", que)
     # sort 'que' according to the 'place' attribute of waiter
     que.sort(key=lambda x: x.place)
     # print("que:", que)
     return que
コード例 #17
0
ファイル: netkeiba.py プロジェクト: shosatojp/gcc
    parser.add_argument('--year', '-y', type=int, required=True)
    parser.add_argument('--queue_size', type=int, default=3)
    parser.add_argument('--wait',
                        '-w',
                        type=int,
                        default=10,
                        help='wait time in seconds')
    parser.add_argument('--dir',
                        '-d',
                        type=str,
                        default='cache',
                        help='cache directory')
    parser.add_argument('--useragent', '-ua', type=str, default='')
    args = parser.parse_args()
    signal.signal(signal.SIGINT, lambda a, b: print('sigint') or exit(1))

    c = Keiba(
        reporter=Reporter(1),
        waiter=Waiter([args.wait]),
        outdir=args.dir,
        useragent=args.useragent,
    )
    if args.type == 'race':
        asyncio.run(c.run(c.collect(args.year, queue_size=args.queue_size)))
    elif args.type == 'horse':
        asyncio.run(
            c.run(c.collect_horse(args.year, queue_size=args.queue_size)))
    else:
        print('invalid type')
        exit(1)
コード例 #18
0
ファイル: exercise01.py プロジェクト: psounis/python
 def test_serve(self):
     w = Waiter("Tom", 5000)
     w.serve(50, self.baristaObj)
     self.assertEqual(w.served_cnt, 50)
コード例 #19
0
 def testWaiterNumberInvalidLower(self):
     iterations = "10 2"
     numbers = "1 3 55 22 42 76 39 7 51 56"
     waiter = Waiter(iterations, numbers)
     piles = waiter.stackPiles()
     self.assertEqual(-1, piles)
コード例 #20
0
 def testPrime(self):
     self.assertTrue(Waiter.isPrime(5))
コード例 #21
0
 def testWaiterQInvalidUpper(self):
     iterations = "10 1201"
     numbers = "27 3 55 22 42 76 39 7 51 56"
     waiter = Waiter(iterations, numbers)
     piles = waiter.stackPiles()
     self.assertEqual(-1, piles)
コード例 #22
0
 def testWaiterSecondArgumentNotOK(self):
     iterations = "10 9"
     numbers = "27 error 55 22 42 76 39 7 51 56"
     waiter = Waiter(iterations, numbers)
     piles = waiter.stackPiles()
     self.assertEqual(-1, piles)
コード例 #23
0
 def testWaiterFirstArgumentNotOK(self):
     iterations = "10 e"
     numbers = "27 17 60 38 67 86 70 86 17 39"
     waiter = Waiter(iterations, numbers)
     piles = waiter.stackPiles()
     self.assertEqual(-1, piles)
コード例 #24
0
ファイル: douyin.py プロジェクト: xrr8417403/douyin-1
class DouYinAPI:
    def __init__(self,
                 proxy_api=PROXY_API,
                 token_file=TOKEN_FILE,
                 token=API_TOKEN):
        self.token = token
        self.proxy_api = proxy_api
        self.token_file = token_file
        self.waiter = Waiter()

    def init(self, db=False):
        self.waiter._check_token_files(self.token_file)
        if db:
            self.waiter._check_token_table()

    def get_tokens(self, count=1):
        tokens = self.waiter.tokens
        if tokens:
            try:
                return [tokens.pop() for _ in range(count)]
            except KeyError:
                raise TokenSetEmpty('No token in the token set.')
        raise NoTokensGenerated(
            'No tokens found.You should generate some tokens before.')

    def get_token_info(self, token, proxy=None):
        try:
            data = api_service(route=ROUTE_INFO_TOKEN,
                               method="get",
                               token=token,
                               proxy=proxy)
            return data
        except Exception as e:
            logger.error(f"{e.__class__.__name__}:{e}")

    def get_new_device_info(self, token, proxy=None):
        data, device_info = gen_device_data()
        try:
            data = api_service(route=ROUTE_CRYPT_DOUYIN,
                               token=token,
                               method="post",
                               data=json.dumps(data),
                               content_type="application/json",
                               proxy=proxy)
            data = base64.b64decode(data['base64_data'])
            resp = requests.post(API_DEVICE_REGISTER,
                                 headers=HEADERS,
                                 data=data,
                                 proxies=proxy)
            content = resp.content.decode("utf-8")
            new_device = json.loads(content)
            new_device['openudid'] = device_info[0]
            new_device['android_id'] = device_info[1]
            new_device['uuid'] = device_info[2]
            new_device['iid'] = new_device['install_id']
            return new_device
        except Exception as e:
            logger.error(f'{e.__class__.__name__}:{e}')

    @force_type({1: dict})
    @choose('feed')
    def get_feed(self, params, token='', device_info={}, proxy=None):
        return params

    @choose('user_info')
    def get_user_info(self, userId, token='', device_info={}, proxy=None):
        params = {"user_id": userId}
        return params

    @choose('user_fans')
    def get_user_fans(self, userId, count=20, device_info={}, proxy=None):
        params = {
            "user_id": userId,
            "count": count,
            "max_time": str(int(time()))
        }
        return params

    @choose('user_videos')
    def get_user_videos(self, userId, count=20, device_info={}, proxy=None):
        params = {"user_id": userId, "max_cursor": 0, "count": count}
        return params

    @choose('user_like')
    def get_user_like(self, userId, count=20, device_info={}, proxy=None):
        params = {"user_id": userId, "max_cursor": 0, "count": count}
        return params

    @choose('video_comments')
    def get_video_comments(self,
                           aweme_id,
                           count=20,
                           device_info={},
                           proxy=None):
        params = {"aweme_id": aweme_id, "cursor": 0, "count": count}
        return params

    def generate_tokens(self,
                        count=MAX_TOKEN_GETS,
                        toDB=False,
                        tname=MongoDB['tokens'],
                        path=None):
        self.waiter.generate_tokens(self.proxy_api, count, toDB, tname, path)
コード例 #25
0
ファイル: main.py プロジェクト: eduard01a10/python_oop
##This is a basic OOP project with python
from person import Person
from chef import Chef
from manager import Manager
from waiter import Waiter
from dishwasher import Dishwasher
from client import Client

if __name__ == "__main__":

    c = Chef("Jesus", 45, "Male")
    m = Manager("Beto", 72, "Male")
    w = Waiter("Eduardo", 25, "Male")
    d = Dishwasher("Sarah", 33, "Female")
    cl = Client("Female")

    print(
        f"{c.name} is the chef name, is {c.age} years old, and is {c.gender}. {c.cook()}"
    )
    print(
        f"{m.name} is the manager name, is {m.age} years old, and is {m.gender}. {m.management()}"
    )
    print(
        f"{w.name} is the waiter name, is {w.age} years old, and is {w.gender}. {w.serve()}"
    )
    print(
        f"{d.name} is the dishwasher name, is {d.age} years old, and is {d.gender}. {d.wash()}"
    )
    print(f"The client is a {cl.gender} and {cl.order()}")
コード例 #26
0
def main():
    waiter = Waiter(LunchMenu(), DinnerMenu())
    waiter.show_menu()
コード例 #27
0
ファイル: exercise01.py プロジェクト: psounis/python
 def test_init(self):
     w = Waiter("Tom", 5000)
     self.assertEqual(w.full_name, "Tom")
     self.assertEqual(w.salary, 5000)
     self.assertEqual(w.served_cnt, 0)
コード例 #28
0
    def setUp(self) -> None:
        self.waiter1 = Waiter("Harry Potter", 150)
        self.waiter1.customers_served = 42

        self.barista1 = Barista("Hermione Granger", 160)
コード例 #29
0
from waiter import Waiter
from item import Item
from menu import Menu

# Creating a menu
# Create a waiter with a menu and add the items
Jared = Waiter("Jared")

Jared.menu.add_item("Pasta", 10)
Jared.menu.add_item("Burger", 12)
Jared.menu.add_item("Smoothie", 5)
Jared.menu.add_item("Salad", 7)
Jared.menu.add_item("Pizza", 15)
Jared.menu.add_item("Large Pizza", 21)
Jared.menu.add_item("Soup of the Day", 8)
Jared.menu.add_item("Falafel Wrap", 11)
Jared.menu.add_item("Curry", 13)
Jared.menu.add_item("Fried Rice", 6)
Jared.menu.add_item("Chips", 3)

print(f"\n      Hi there, I'm {Jared.name}. Can I take your order? ")

# This code will run until we insert 4 as a choice
while True:
    choice = input("""
            1. Show menu
            2. Order something
            3. Show current order list
            4. Finish with ordering
            ->  """)
コード例 #30
0
ファイル: runtests.py プロジェクト: Ricyteach/mypy
class Driver:

    def __init__(self, *, whitelist: List[str], blacklist: List[str],
            lf: bool, ff: bool,
            arglist: List[str], pyt_arglist: List[str],
            verbosity: int, parallel_limit: int,
            xfail: List[str], coverage: bool) -> None:
        self.whitelist = whitelist
        self.blacklist = blacklist
        self.arglist = arglist
        self.pyt_arglist = pyt_arglist
        self.verbosity = verbosity
        self.waiter = Waiter(verbosity=verbosity, limit=parallel_limit, xfail=xfail, lf=lf, ff=ff)
        self.versions = get_versions()
        self.cwd = os.getcwd()
        self.env = dict(os.environ)
        self.coverage = coverage

    def prepend_path(self, name: str, paths: List[str]) -> None:
        old_val = self.env.get(name)
        paths = [p for p in paths if isdir(p)]
        if not paths:
            return
        if old_val is not None:
            new_val = os.pathsep.join(itertools.chain(paths, [old_val]))
        else:
            new_val = os.pathsep.join(paths)
        self.env[name] = new_val

    def allow(self, name: str) -> bool:
        if any(f in name for f in self.whitelist):
            if not any(f in name for f in self.blacklist):
                if self.verbosity >= 2:
                    print('SELECT   #%d %s' % (len(self.waiter.queue), name))
                return True
        if self.verbosity >= 3:
            print('OMIT     %s' % name)
        return False

    def add_mypy_cmd(self, name: str, mypy_args: List[str], cwd: Optional[str] = None) -> None:
        full_name = 'check %s' % name
        if not self.allow(full_name):
            return
        args = [sys.executable, '-m', 'mypy'] + mypy_args
        args.append('--show-traceback')
        args.append('--no-site-packages')
        self.waiter.add(LazySubprocess(full_name, args, cwd=cwd, env=self.env))

    def add_mypy_modules(self, name: str, modules: Iterable[str], cwd: Optional[str] = None,
                         extra_args: Optional[List[str]] = None) -> None:
        args = extra_args or []
        args.extend(list(itertools.chain(*(['-m', mod] for mod in modules))))
        self.add_mypy_cmd(name, args, cwd=cwd)

    def add_pytest(self, files: List[Tuple[str, str]], coverage: bool = True) -> None:
        pytest_files = [name for kind, name in files
                        if self.allow('pytest {} {}'.format(kind, name))]
        if not pytest_files:
            return
        pytest_args = pytest_files + self.arglist + self.pyt_arglist
        if coverage and self.coverage:
            args = [sys.executable, '-m', 'pytest', '--cov=mypy'] + pytest_args
        else:
            args = [sys.executable, '-m', 'pytest'] + pytest_args

        self.waiter.add(LazySubprocess('pytest', args, env=self.env,
                                       passthrough=self.verbosity),
                        sequential=True)

    def add_flake8(self, cwd: Optional[str] = None) -> None:
        name = 'lint'
        if not self.allow(name):
            return
        largs = ['flake8', '-j0']
        env = self.env
        self.waiter.add(LazySubprocess(name, largs, cwd=cwd, env=env))

    def list_tasks(self) -> None:
        for id, task in enumerate(self.waiter.queue):
            print('{id}:{task}'.format(id=id, task=task.name))
コード例 #31
0
    disease1 = Disease('Citrus allergy', [orange, lemon])
    disease2 = Disease('Strawberry allergy', [strawberry])
    disease3 = Disease('Lactose intolerance', [milk, egg])
    disease4 = Disease('Chocolate allergy', [chocolate])
    print(disease1)

    customer = Customer('Robert', 'Smith', '*****@*****.**',
                        [disease4])
    print(customer)

    menu_customer = customer.get_personal_menu(restaurant)
    for dish in menu_customer:
        print(dish)

    waiter = Waiter('Elliot', 'Smith', 35.7)
    print(waiter)

    order1 = waiter.take_order(customer, [dish2, dish4])
    print(order1)

    print(order1.get_full_price())

    waiter.bring_order(order1)
    order1.pay_for_order(60)

    print(waiter.get_salary())

    restaurant.waiters = [waiter]
    restaurant.orders = [order1]
コード例 #32
0
 def testNotPrime(self):
     self.assertFalse(Waiter.isPrime(4))
コード例 #33
0
    parser = argparse.ArgumentParser('wear')
    parser.add_argument('url', action='store', help='URL')
    parser.add_argument('--pagestart', '-ps', type=int, required=True)
    parser.add_argument('--pageend', '-pe', type=int, required=True)
    parser.add_argument('--useragent', '-ua', type=str, default='')
    parser.add_argument('--waitlist', '-wl', type=str, default='wait.json')
    parser.add_argument('--outdir', '-o', type=str, required=True)
    parser.add_argument('--loglevel',
                        '-ll',
                        default=2,
                        type=int,
                        help='log level')
    parser.add_argument(
        '--wait',
        '-w',
        default='5',
        nargs='+',
        type=str,
        help=
        'interval for http requests. default is none. `-w 0.5` `-w random 1 2.5`'
    )
    args = parser.parse_args()

    c = WearCollector(reporter=Reporter(args.loglevel),
                      waiter=Waiter(args.wait, args.waitlist),
                      outdir=args.outdir,
                      useragent=args.useragent)
    asyncio.run(c.run(c.user_collector(args.url, args.pagestart,
                                       args.pageend)))