async def ducksay(self, ctx: Context, message: str) -> None: """Duck says what?""" MAX_LEN = 50 data = message.split(' ') res = [] curr = "" for val in data: new = curr + ' ' + val if curr else curr + val if len(new) >= MAX_LEN: res.append(curr) curr = "" new = curr + val curr = new if curr: res.append(curr) max_len = len(zz.of(res).max(len)) if len(res) > 1: delim = zz.empty().chain(zz.of(["/\\"]), zz.repeat("||", n=len(res) - 2), zz.of(["\\/"])) else: delim = zz.repeat("<>") final = '' final += "```\n" final += " " + "_" * (max_len + 2) + " \n" for d, elem in zip(delim, res): elem += " " * (max_len - len(elem)) final += d[0] + " " + elem + " " + d[1] + "\n" final += " " + "-" * (max_len + 2) + " \n" final += " \\\n" final += " \\\n" final += " \\ >()_\n" final += " (__)__ _\n" final += "```" await ctx.send(final)
def test_each_4(self): # Singleton list to work around lack of nonlocal support in Python 2 n = [0] def f(x): n[0] += x zz.of([10, 20, 30, 40]).each(f) self.assertEqual(n[0], 100)
def test_consume_5(self): x = {1: -10} def foo(y): x[1] = y return True zz.of([1, 2, 3]).filterfalse(foo) # Don't consume self.assertEqual(x[1], -10)
def test_consume_3(self): x = {1: -10} def foo(y): x[1] = y return y zz.of([1, 2, 3]).map(foo) # Don't consume self.assertEqual(x[1], -10)
def test_consume_2(self): x = {1: -10} def foo(y): x[1] = y return y zz.of([1, 2, 3]).map(foo).consume() self.assertEqual(x[1], 3)
async def volunteer(self, ctx: Context, role: OptionalChecked[discord.Role] = None): """Randomly selects a player""" choices = zz.of(ctx.bot.get_all_members()) if role: choices = choices.filter( lambda x: zz.of(x.roles).find(_1.id == role.id)) choices = choices.list() member = random.choice(choices) await ctx.send("I choose {}!".format(member.name))
def test_apply_5(self): ex = {'foo': 0} def f(x): # nonlocal ex (can't do this, for Python 2 compatibility) ex['foo'] += 1 # Any call to apply calls the function exactly once zz.range(10).apply(f) zz.of([1, 2, 3]).apply(f) zz.empty().apply(f) self.assertEqual(ex['foo'], 3)
async def add(self, ctx: Context, deck: Deck, *cards: str) -> None: """Add one or more cards to a deck. This adds several cards to the top of the deck in order, so that the last card listed will be at the top of the deck. If you want to add several copies of the same card, then you may find '!deck addmany' more convenient. Admins and deck owners only. """ if zz.of(cards).any(lambda x: len(x) > MAX_CARD_LEN): raise error.InputsTooLarge() if deck.total_cards() + len(cards) > deck.data.max_deck_size: await ctx.send( f"The limit on this deck is {deck.data.max_deck_size}. If you need more cards, you can ask an admin to increase the limit." ) return for card in cards: deck.place_atop_deck(card) if len(cards) == 0: await ctx.send("You didn't specify any cards.") elif len(cards) == 1: await ctx.send("Okay, I added that card.") else: await ctx.send("Okay, I added those cards.")
def find_member(server: discord.Guild, name: str) -> Optional[discord.Member]: name = name.lower() def match(person: discord.Member) -> bool: return (person.name.lower() == name or person.display_name.lower() == name) return zz.of(server.members).find(match)
def test_chain_lazy_4(self): # chain is lazy def foo(): arr = [] for i in zz.count(1): arr.append(i) yield arr self.assertEqual(zz.of([9, 9, 9]).chain_lazy(foo()).take(9).list(), [9, 9, 9, 1, 1, 2, 1, 2, 3])
async def owner_list(self, ctx: Context, deck: Deck) -> None: """List all owners of a deck.""" if ctx.message.guild: result = zz.of(owner_list(ctx.message.guild, deck)).map(_1.display_name).list() else: result = [] await ctx.send("Members who own the deck {}: {}".format( deck.data.name, ', '.join(result)))
async def owner_list(self, ctx: Context, role: ManagedRole) -> None: """List all owners of a role.""" if ctx.message.guild: result = zz.of(owner_list(ctx.message.guild, role)).map(_1.display_name).list() else: result = [] await ctx.send("Members who own the role {}: {}".format( role.name, ', '.join(result)))
async def spam_check(self, message: discord.Message) -> None: if message.author == self._bot.user: return if json_data.linky and contains_link(message.content): role = json_data.linky if isinstance(message.author, discord.Member): if role not in zz.of(message.author.roles).map(_1.id): await message.delete() await message.author.send("You don't have permission to post links. Feel free to ask an admin for this permission :)") await log_message(self._bot, "{} (in channel #{}) just tried to post the link: {}".format(message.author, message.channel, message.content))
def __init__(self) -> None: with open('words.txt') as file: self.words = zz.of(file).map(_1[:-1]).list() random.shuffle(self.words)
#!/usr/bin/python3 import alakazam as zz from alakazam import _1, _2, _3, _4, _5 from collections import defaultdict NUMBER = 5 cubes = [] cube_cache = defaultdict(lambda: 0) def is_permutation(a, b): return sorted(str(a)) == sorted(str(b)) for i in zz.count(1).map(_1 ** 3): print(i) i1 = str(sorted(str(i))) cubes.append(i) cube_cache[i1] += 1 if cube_cache[i1] == NUMBER: print(zz.of(cubes).filter(lambda x: is_permutation(x, i)).foldr_lazy(lambda x, _: x)) break
def test_of(self): iterable = zz.of([1, 2, 3, 4, 5]) self.assertEqual(iterable.list(), [1, 2, 3, 4, 5])
def test_foldl_5(self): # init value goes on the left func = lambda x, y: x - y self.assertEqual(zz.of([1, 2, 3, 4]).foldl(func, init=100), 90)
def owner_list(server: discord.Guild, deck: Deck) -> List[discord.Member]: return zz.of(deck.data.owners).map(server.get_member).filter(_1).list()
def test_tuple(self): tup = ("foo", "bar", 10, 20, None) self.assertEqual(zz.of(tup).tuple(), tup)
async def template_list(self, ctx: Context) -> None: """List all available deck templates.""" templates = zz.of(DeckTemplate.all()).map( lambda t: f"{t.name} ({len(t.cards)})").list() await ctx.send("The following deck templates are available:\n```\n" + '\n'.join(templates) + "\n```")
def test_sorted_5(self): # Lexicographic ordering (reversed) self.assertEqual( zz.of([10, 9, 11]).sorted(key=str, reverse=True), [9, 11, 10])
def test_list(self): lst = ["foo", "bar", 10, 20, None] self.assertEqual(zz.of(lst).list(), lst)
def test_sorted_3(self): self.assertEqual(zz.of([10, 9, 11]).sorted(), [9, 10, 11])
def test_sorted_4(self): # Lexicographic ordering self.assertEqual(zz.of([10, 9, 11]).sorted(key=str), [10, 11, 9])
def test_sorted_2(self): self.assertEqual( zz.of([3, 1, 2, 0]).sorted(reverse=True), [3, 2, 1, 0])
def test_sorted_1(self): self.assertEqual(zz.of([3, 1, 2, 0]).sorted(), [0, 1, 2, 3])
def test_foldr_1(self): func = lambda x, y: y + x string = "CBA" lst = ["A", "B", "C"] self.assertEqual(zz.of(lst).foldr(func), string)
def name_to_role(bot: commands.Bot, name: str) -> discord.Role: return zz.of(bot.guilds).map(_1.roles).flatten().find(_1.name == name)
def test_foldr_4(self): # Should fold from the right func = lambda x, y: x - y self.assertEqual(zz.of([1, 2, 3, 4]).foldr(func), -2)
def owner_list(server: discord.Guild, role: discord.Role) -> List[discord.Member]: if role.id not in json_data.roles: return [] data = json_data.roles[role.id] return zz.of(data.owners).map(server.get_member).filter(_1).list()
def test_set(self): data = {"foo", "bar", 10, 20, None} self.assertEqual(zz.of(data).set(), data)