Пример #1
0
def pick_ingredient():
    # This is horrifyingly inefficient
    item = choice(list(components['ingredients'].items()))
    item[1]['name'] = item[0]
    item = item[1]

    part = (choice(list(components['parts'][item['type']].items()))
            if item['parts'] else None)

    # Item types: animal, plant, fungus, solid, liquid, intangible
    # Part types: solid, liquid, intangible
    type = part[1] if part else item['type']

    attributes = components['attributes']['general']

    if type != 'intangible':
        count, pluralize = choice(list(zip(counts, plurals)))
    else:
        count, pluralize = None, False

    if type in ('solid', 'liquid'):
        # Note no +=! For lists, += modifies the original list!
        attributes = attributes + components['attributes'][type]
        attribute = choice(attributes) if maybe(0.25) else None
        measure = choice(components['measures'][type])

        ingredient = f'{part[0]} of {item["name"]}' if part else item['name']

        item = {'item': ingredient, 'type': type}

        ingredient = ' '.join((
            str(count),
            plural(measure) if pluralize else measure,
            f'{attribute} {ingredient}' if attribute else ingredient,
        ))

        if maybe(0.2):
            ingredient += f', {choice(components["preparations"][type])}'

    else:
        ingredient = item['name']

        if part:
            ingredient = f'{part[0]} of {ingredient}'
        elif type == 'animal' and flip():
            ingredient = f'live {ingredient}'

        if pluralize:
            ingredient = plural(ingredient)

        item = {'item': ingredient, 'type': type}

        if maybe(0.25):
            ingredient = f'{choice(attributes)} {ingredient}'

        if count:
            ingredient = f'{count} {ingredient}'

    return item, ingredient
Пример #2
0
def test_iteration():
    for v in maybe(1):
        assert v == 1
        break
    else:
        pytest.fail('Expected value to be unpacked')

    for _ in maybe(None):
        pytest.fail('Expected no value to be unpacked')
    assert True
Пример #3
0
def test_delegators():
    class Bunch:
        def __init__(self, **kwargs):
            self.__dict__.update(kwargs)

    obj = maybe(Bunch(x=Bunch(y=Bunch(z=1))))
    assert obj._.x._.y._.z.val == 1

    obj = maybe(Bunch(x=Bunch(y=None)))

    assert obj._.x._.y._.z.is_nothing
Пример #4
0
def syllable(first=True, last=True):
    """
    Usually start with a consonant (or consonant combination), add vowel,
    optionally add another vowel, and optionally end with a consonant.
    """
    initial = (choice(INITIAL if first else INITIAL +
                      TERMINAL) if not first or maybe(0.75) else '')
    vowel = choice(VOWELS)
    extension = (choice_without(VOWELS, vowel if vowel not in 'eo' else None)
                 if maybe(0.25) else '')
    terminal = choice(TERMINAL) if last and maybe(0.75) else ''

    return initial + vowel + extension + terminal
Пример #5
0
def generate_cover(title, authors):
    cover = f'## {title}\n\n### {authors[0]}'

    if maybe(0.2):
        cover += f'\n\n{choice(books["editions"]).capitalize()} Edition'

    for role in books['roles']:
        if maybe(0.2):
            cover += f'\n\n{role.capitalize()} by {name()}'

    contributors = oxford(authors[2:])
    cover += f'\n\nWith thanks to {contributors} for their contributions.'

    return cover
Пример #6
0
def test_monad_low():
    def f(x):
        return maybe(x + 1)

    def g(x):
        return maybe(x + 2)

    # 1. bind(unit(x), f) === f(x)


    assert maybe(1).flatmap(f) == f(1)

    # 2. bind(m, unit) === m
    assert maybe(1).flatmap(maybe) == maybe(1)

    # 3. bind(bind(m, f), g) === bind(m, x => bind(f(x), g))
    assert maybe(1).flatmap(f).flatmap(g) == maybe(1).flatmap(lambda x: f(x).flatmap(g))
Пример #7
0
def load_tests(refs, **kwargs):
    ref_test = {}
    basedir = maybe(kwargs, 'basedir', None)
    verbose = maybe(kwargs, 'verbose', False)

    #if not hasattr(refs,'next'):
    #    refs = [refs]
    try:
        for ref in refs:
            ref_test = load_test(ref,**kwargs)
            if not hasattr(ref_test,'items'):
                print ref_test
                ref_test = dict(ref_test)
    except SyntaxError as e:
        stderr.write("Could not parse reference file {}\n".format(ref.name))
        exit(1)

    return ref_test
Пример #8
0
def test_lazyness():
    add_called = False
    def add1(val):
        nonlocal add_called
        add_called = True
        return val + 1

    assert maybe.lazy(v
        for x in maybe(None)
        for v in add1(x)).is_nothing

    assert not add_called
Пример #9
0
def load_test(ref,**kwargs):
    (basedir,name) = path.split(ref.name)
    if 'basedir' in kwargs:
        basedir = kwargs['basedir']
        name = ref.name
    verbose = maybe(kwargs,'verbose', False)

    ref_test = literal_eval(ref.read())
    ref_test['basedir'] = basedir
    if 'problems' in ref_test:
        if verbose:
            stderr.write("Reading problemset file {}\n".format(ref.name))
        ref_test = load_problem_set(ref_test,basedir)
    return (name,ref_test)
Пример #10
0
def questionFun(emailContact):
    emailContact = emailContact
    print("""
	  _  _                _                   _                    _     _              _   
	 | || |_____ __ __   | |_ ___     __ _ __| |__   __ _     __ _(_)_ _| |    ___ _  _| |_ 
	 | __ / _ \ V  V /   |  _/ _ \   / _` (_-< / /  / _` |   / _` | | '_| |   / _ \ || |  _|
	 |_||_\___/\_/\_/     \__\___/   \__,_/__/_\_\  \__,_|   \__, |_|_| |_|   \___/\_,_|\__|
	                                                         |___/                          
	""")

    answer = input("Will you go on a date? \n(yes, no, maybe): ")

    answer = answer.lower()
    if answer == "yes" or answer == "y":
        yes.yes(emailContact)
    elif answer == "no" or answer == "n":
        no.no(emailContact)
    elif answer == "maybe" or answer == "m":
        maybe.maybe(emailContact)
    else:
        confirmEmail.ians(emailContact)
        os.system("clear")
        print('Not a valid answer, please try again')
        questionFun(emailContact)
Пример #11
0
def test_getitem():
    d = { 'x': { 'y': { 'z': 1 }, 'p': None } }
    assert maybe(d)._['x']._['y']._['z'].val == 1
    assert maybe(d)._['x']._['p']._['q'].is_nothing

    assert maybe(d)._['x']._['y']._['a'].is_nothing

    l = [[1], [2], None]
    assert maybe(l)._[0]._[0].val == 1
    assert maybe(l)._[0]._[1].is_nothing
    assert maybe(l)._[2]._[1].is_nothing
Пример #12
0
def parse_actions(actions, **kwargs): 
    stderr.write("kwargs keys: {}\n".format(kwargs.keys()))
    to_review = []
    action_callers = {'review': lambda x,**k: to_review.append(x), 'suggest': on_suggest, 'test': on_test}
    verbose = maybe(kwargs,'verbose',False)
    if verbose:
        stderr.writelines("action -- {}\n".format(action) for action in actions)
    for (action, args) in imap(lambda x: x.split(':'), actions):
        try:
            action_callers[action](args.strip(), **kwargs)
        except KeyError as e:
            stderr.write("Action '{}' is not implemented\n".format(action))

    stderr.write("Reviewing: {}\n".format(to_review))
    kwargs['nowait']=True
    for review in to_review[:-1]:
        on_review(review, **kwargs)
    kwargs['nowait']=False
    on_review(to_review[-1], **kwargs)
Пример #13
0
def grouped_directions(liquid, solid, other):
    directions = choice([
        f'Combine {oxford(liquid)}.',
        f'Add {oxford(liquid)}, stirring gently.',
        f'Beat together {oxford(liquid)} until frothy.',
        f'Pour {oxford(liquid)} into prepared vessel.',
    ])

    if maybe(0.33):
        directions += ' Bring to a boil, stirring ' + choice([
            'vigorously.', 'continuously.', 'occasionally.', 'intermittently.',
            'once.'
        ])
    elif flip():
        directions += (
            ' Lower the temperature until the mixture begins to congeal.')

    next_direction = choice([
        f'Stir in {oxford(solid)}, individually.',
        f'Blend in {oxford(solid)}, stirring until fully dissolved.',
        f'Add {oxford(solid)}.' + (' Do not overmix.' if flip() else ''),
        f'Beat in {oxford(solid)} until only a few chunks remain.',
    ])

    directions += '\n\n' + optional_action(next_direction)

    if other:
        next_direction = ' '.join([
            choice([
                f'Add {i}.',
                f'Carefully add {i}.',
                f'Cautiously add {i}.',
                f'Blend in {i}.',
                f'Fold in {i}.',
                f'Combine with {i}.',
                f'Add {i} and mix thoroughly.',
            ]) for i in other
        ])

        directions += '\n\n' + optional_action(next_direction)

    return directions
Пример #14
0
def generate_page(authors):
    # Generate spell title
    spell = choice(list(spells['spells'].keys()))
    title = choice(spells['spells'][spell])

    afflicted = choice(parts) if spell in ('blight', 'cure') else None
    target = plural(choice(summons))

    if flip():
        title = f'{choice(spells["attributes"])} {title}'

    if spell == 'cure':
        title += ' for '
    else:
        title += ' of '

    if spell == 'summoning':
        title += target
    elif spell in ('blight', 'cure'):
        title += f'{choice(spells["maladies"])} {afflicted}'
    else:
        title += choice(spells['subjects'])

    if maybe(0.2):
        title = f"{choice(authors).split()[0]}'s {title}"

    title = titlecase(title)

    # Generate list of ingredients
    items, ingredients = generate_ingredients()
    ingredients = f'\n* ' + '\n* '.join(ingredients)

    # Generate directions
    directions = generate_directions(items, spell, afflicted, authors, target)

    page = '\n\n'.join((
        f'## {title}',
        f'### Ingredients\n{ingredients}',
        f'### Directions\n\n{directions}',
    ))

    return page
Пример #15
0
def collect_problem(path, problem, **kwargs):
   verbose = False
   if 'verbose' in kwargs:
      verbose = kwargs['verbose']

   points=0
   comments = []
   total_points = maybe(problem, 'points', int(0))
   try:
      with open(os.path.join(path,problem['src']), 'r') as f:
         (points,comments) = collect_points(f)
   except IOError as e:
      points = -total_points
      comments.append((problem['src'],0,'Could not find source file\n'))

   subtotal = total_points+points
   if verbose:
      sys.stderr.write("\tpoints for {}: {}/{}\n".format(problem['src'],subtotal,total_points))
      sys.stderr.writelines("\t{}:{} {}".format(fname,lineno,line) for (fname,lineno,line) in comments if not line.strip() == '###DKM')
   return (subtotal, total_points, comments)
Пример #16
0
def individual_directions(items):
    directions = choice([
        f'Start with {items[0]["item"]}.',
        f'To begin, add {items[0]["item"]}.',
        f'First, add {items[0]["item"]}.',
        f'Add {items[0]["item"]} to the prepared vessel.',
    ])

    for i in items[1:]:
        if i['type'] == 'liquid':
            next_direction = choice([
                f'Add {i["item"]}.',
                f'Pour in {i["item"]}.',
                f'Mix in {i["item"]}.',
            ]) + (f' Stir {choice(["vigorously", "gently", "once"])}.'
                  if flip() else '')

        elif i['type'] == 'solid':
            next_direction = choice([
                f'Add {i["item"]}.',
                f'Mix in {i["item"]}.',
                f'Fold in {i["item"]}.',
            ])

        else:
            next_direction = choice([
                f'Add {i["item"]}.',
                f'Carefully add {i["item"]}.',
                f'Cautiously add {i["item"]}.',
                f'Blend in {i["item"]}.',
                f'Fold in {i["item"]}.',
                f'Combine with {i["item"]}.',
                f'Add {i["item"]} and mix thoroughly.',
            ])

        directions += '\n\n' if maybe(0.2) else ' '
        directions += optional_action(next_direction, 0.2)

    return directions
Пример #17
0
 def g(x):
     return maybe(x + 2)
Пример #18
0
def test_nothing_maps_to_nothing():
    assert maybe(None).map(lambda x: x + 1) == nothing
Пример #19
0
 def f(x):
     return maybe(x + 1)
Пример #20
0
 def wrapper(value: Maybe[T]) -> Maybe[U]:
     try:
         return maybe(f(value))
     except Exception:
         return Nothing()
Пример #21
0
def test_map_applies_func_to_just_val():
    assert maybe(1).map(lambda x: x + 1) == maybe(2)
Пример #22
0
def optional_action(direction, chance=0.5):
    return action() + uncapitalize(direction) if maybe(chance) else direction
Пример #23
0
def test_unpacking():
    val, exists = maybe(1).unpack()
    assert (val, exists) == (1, True)
    val, exists = maybe(None).unpack()
    assert (val, exists) == (None, False)
Пример #24
0
def test_flatmap_accepts_funcs_returning_maybe():
    assert maybe(1).flatmap(lambda x: maybe(x + 1)) == maybe(2)
Пример #25
0
         for commented_file in commented_files:
            if not os.path.basename(commented_file) in [ problem['src'] for problem in homework['problems']]:
               homework['problems'].append({'src': os.path.basename(commented_file)})
      results = [ collect_problem(path,problem,verbose=args.verbose) for problem in homework['problems'] ]
      
      comments_file = scholar.comments_file(pid)

      if args.verbose:
         sys.stderr.write("Writing comments to {}\n".format(comments_file))
         
      student_total = 0
      f = StringIO.StringIO()
      for (problem, (subtotal, outof, comments)) in zip(homework['problems'], results):
         if outof > 0:
            point_report="{}/{}".format(subtotal,outof)
         else:
            point_report="{}".format(subtotal)

         f.write("## {}: {}\n\n".format(problem['src'], point_report))
         if args.verbose:
            sys.stderr.write("{} comments: {}\n".format(problem['src'], comments))
         f.writelines("\tline {}: {}\n".format(lineno, comment.strip()) for (fname,lineno,comment) in comments if not comment.strip() == '###DKM' )
         f.write("\n")
         student_total += subtotal
      f.write("\n*subtotal:* {}/{}\n".format(student_total, sum(maybe(x, 'points', 0) for x in homework['problems']))) 
      if args.verbose:
         sys.stderr.write("Markdown comments:\n{}".format(f.getvalue()))
      scholar.write_comments(pid,f.getvalue())
      f.close()
      print "{} {}".format(pid,student_total)
Пример #26
0
def test_bool():
    assert maybe(1)
    assert not maybe(None)
Пример #27
0
def  test_get():
    assert maybe(1).get() == 1
    assert maybe(None).get(-1) == -1
Пример #28
0
 def __init__(self, subtries=None):
     if subtries is None:
         subtries = {}
     self.subtries = maybe(subtries)