Example #1
0
 def dispatch_line(self, line):
     debug(line)
     if line.startswith('PING'):
         self.sendstring("PONG %s\r\n" % line[5:])
     if self.state == CONNECTED:
         self.sendstring("NICK %s\r\n" % (self.NICK,))
         self.sendstring("USER %s %s bla :%s\r\n" % (self.IDENT, self.HOST, self.REALNAME))
         self.state = NICK_SENT
     elif self.state == NICK_SENT:
         if line.startswith(':'):
             server, code, args = self.parse_line(line)
             if code == '001':
                 self.sendstring("JOIN %s\r\n" % (self.CHANNEL,))
                 self.state = JOINING
     elif self.state == JOINING:
         if line.startswith(':'):
             source, cmd, args = self.parse_line(line)
             if cmd == 'JOIN':
                 assert args[1:] == self.CHANNEL
                 self.state = JOINED
     elif self.state == JOINED:
         if line.startswith(':'):
             source, cmd, dest, args = self.parse_line(line, 4)
             self.module.handle(source, cmd, dest, args)
         if line.startswith('ERROR'):
             sys.exit(0)
Example #2
0
 def parse_command(self, sender, s):
     # debug("command: %r" % (s,))
     if s.startswith(':`'):
         if ' ' in s:
             command, args = s[2:].split(' ', 1)
         else:
             command = s[2:]
             args = ()
         debug("command = %r" % (command,))
         self.dispatch_command(sender, command, args)
Example #3
0
 def check_updated_module(self):
     statinfo = os.stat(self.module_filename)
     if statinfo.st_mtime > self._module_timestamp:
         debug("%s has changed, reloading" % (self.module_filename,))
         try:
             imp.reload(self._module)
         except:
             traceback.print_exc()
             return
         self.init_module_handler()
         self._module_timestamp = statinfo.st_mtime
Example #4
0
 def handle(self, source, cmd, dest, args):
     # debug("source=%r; cmd=%r; args=%r" % (source, cmd, args))
     start = time.time()
     recipient = self.parse_recipient(source, dest)
     try:
         if cmd == 'PRIVMSG':
             if recipient.nick == 'zarq':
                 # yay admin
                 # debug("YAY ADMIN")
                 self.parse_command(recipient, args)
             elif recipient.nick == 'f00f':
                 self.parse_f00f(recipient, args)
         elif cmd == 'INVITE':
             if recipient.nick == 'zarq':
                 self.parse_invite(recipient, args)
     except Exception as ex:
         traceback.print_exc()
         recipient = Recipient('#ivo', 'zarq')
         self.respond_publicly(recipient, "HALP %r" % (ex,))
     debug("Handled in %.3fs" % (time.time() - start,))
Example #5
0
 def sendstring(self, string):
     debug(string, end='')
     self.send_queue.put(string.encode('utf-8'))
Example #6
0
def gogogalgje(raad, template):
    alphabet = set('abcdefghijklmnopqrstuvwxyz')
    words = all_words
    letters_die_erin_zitten = set()
    letters_die_er_niet_in_zitten = set()
    succes = False

    while True:
        # Itereren vanaf hier
        match = create_re_from_template(template, letters_die_erin_zitten)
        # debug("Rekenen...")

        letters = defaultdict(set)
        possible_outcomes_unique = defaultdict(set)
        possible_outcomes_all = defaultdict(list)
        possible_outcomes_astrid = defaultdict(lambda: defaultdict(lambda: 0))
        new_words = set()
        for word in words:
            add = True
            for letter in letters_die_er_niet_in_zitten:
                if letter in word:
                    add = False
                    break
            for letter in letters_die_erin_zitten:
                if letter not in word:
                    add = False
                    break
            if add:
                if match.match(word):
                    new_words.add(word)
        words = new_words

        # debug("Letters: %s" % ("".join(letters_die_erin_zitten),))
        # debug("Woorden: (%d) %s" % (len(words), ",".join(list(words)[:20]),))
        if len(words) == 1:
            print("Het woord is: %s" % (list(words)[0],))
            resultaat, new_template = raad(list(words)[0], template)
            assert resultaat == True
            succes = True
            return succes, list(words)[0]
        if len(words) == 0:
            print("Ik weet het niet!")
            succes = False
            return succes, None

        if template in cache and cache[template] in alphabet:
            # debug("In cache")
            top_letter = cache[template]
        else:
            # debug("Not in cache, analyzing...")
            for word in words:
                for letter in alphabet:
                    if letter in word:
                        letters[letter].add(word)
                        outcome = predict_outcome(template, word, letter)
                        possible_outcomes_unique[letter].add(outcome)
                        possible_outcomes_all[letter].append(outcome)
                        possible_outcomes_astrid[letter][outcome] += 1

            # options_letters = []
            # total_letters = len(words)
            # for letter in letters:
            #     count = len(letters[letter])
            #     # total_letters += count
            #     options_letters.append((count, letter))

            # options_letters = list(sorted(options_letters))
            # target_letters = total_letters / 2
            # debug("Possible outcomes (letters): %r" % (letters,))
            # debug("%d mogelijke uitkomsten, doel is %d (letters)" % (total_letters, target_letters))
            # debug("Options (letters): %r" % (",".join([repr((letter, count)) for count, letter in options_letters]),))
            # optoptions_letters = list()
            # for optioncount, optionletter in options_letters:
            #     optoptions_letters.append((abs(optioncount - target_letters), optionletter))
            # optoptions_letters = list(sorted(optoptions_letters))
            # debug("Optimale options (letters): %r" % (",".join([repr((letter, dist)) for dist, letter in optoptions_letters]),))

            # options_all = []
            # total_all = 0
            # for letter in possible_outcomes_all:
            #     count = len(possible_outcomes_all[letter])
            #     total_all += count
            #     options_all.append((count, letter))

            # options_all = list(sorted(options_all))
            # target_all = total_all / 2
            # debug("Possible outcomes (all): %r" % (possible_outcomes_all,))
            # debug("%d mogelijke uitkomsten, doel is %d (all)" % (total_all, target_all))
            # debug("Options (all): %r" % (",".join([repr((letter, count)) for count, letter in options_all]),))
            # optoptions_all = list()
            # for optioncount, optionletter in options_all:
            #     optoptions_all.append((abs(optioncount - target_all), optionletter))
            # optoptions_all = list(sorted(optoptions_all))
            # debug("Optimale options (all): %r" % (",".join([repr((letter, dist)) for dist, letter in optoptions_all]),))

            options_astrid = []
            total_astrid = len(words)
            for letter in possible_outcomes_astrid:
                p_sum = 0.0
                for option in possible_outcomes_astrid[letter]:
                    p_positie = float(possible_outcomes_astrid[letter][option]) / total_astrid
                    # debug("letter=%r, optie=%r, n=%d, p=%.3f" % (
                    #     letter, option, possible_outcomes_astrid[letter][option], p_positie))
                    p_sum += p_positie * ln(p_positie)
                p_nergens = 1.0 - (float(sum(possible_outcomes_astrid[letter].values()))) / total_astrid
                if p_nergens == 0.0:
                    value = 0.0
                else:
                    value = (p_sum + p_nergens * ln(p_nergens)) / p_nergens
                options_astrid.append((value, letter))

            options_astrid = list(sorted(options_astrid))
            # debug("Possible outcomes (astrid): %r" % (possible_outcomes_astrid,))
            # debug("%d mogelijke uitkomsten, doel is -inf (astrid)" % (total_astrid,))
            # debug("Options (astrid): %r" % (",".join([repr((letter, count)) for count, letter in options_astrid]),))
            optoptions_astrid = list()
            for optioncount, optionletter in options_astrid:
                optoptions_astrid.append((abs(optioncount), optionletter))
            optoptions_astrid = list(sorted(optoptions_astrid, reverse=True))
            debug("Optimale options (astrid): %r" % (",".join([repr((letter, dist)) for dist, letter in optoptions_astrid]),))

            # options_unique = []
            # total_unique = 0
            # for letter in possible_outcomes_unique:
            #     count = len(possible_outcomes_unique[letter])
            #     total_unique += count
            #     options_unique.append((count, letter))

            # options_unique = list(sorted(options_unique))
            # target_unique = total_unique / 2
            # debug("Possible outcomes (unique): %r" % (possible_outcomes_unique,))
            # debug("%d mogelijke uitkomsten, doel is %d (unique)" % (total_unique, target_unique))
            # debug("Options (unique): %r" % (",".join([repr((letter, count)) for count, letter in options_unique]),))
            # optoptions_unique = list()
            # for optioncount, optionletter in options_unique:
            #     optoptions_unique.append((abs(optioncount - target_unique), optionletter))
            # optoptions_unique = list(sorted(optoptions_unique))
            # debug("Optimale options (unique): %r" % (",".join([repr((letter, dist)) for dist, letter in optoptions_unique]),))

            top_letter = optoptions_astrid[0][1]

        pogingen.append(top_letter)

        words_met_letter = len(letters[top_letter])
        # debug("Beste letter: %s (%d van %d, %.2f%%)" % (
        #     top_letter,words_met_letter, len(words),
        #     100.0 * float(len(letters[top_letter])) / len(words)))
        resultaat, new_template = raad(top_letter, template)
        if resultaat == True:
            # letter zat erin
            letters_die_erin_zitten.add(top_letter)
            if template not in cache:
                cache[template] = top_letter
        else:
            letters_die_er_niet_in_zitten.add(top_letter)
        template = new_template

        alphabet.remove(top_letter)
Example #7
0
def save_cache():
    debug("Cache schrijven...")
    with open('cache', 'w') as f:
        for template, letter in cache.items():
            f.write("%s%s\n"  % (letter, template))
Example #8
0
from collections import defaultdict
import atexit
import re
from math import log as ln
from galgje_utils import debug

pogingen = []
cache = {}

debug("Woorden inlezen...")
all_words = set()
with open('dutch', 'r') as f:
    for line in f:
        word = line.strip().lower()
        all_words.add(word)

debug("Cache inlezen...")
with open("cache", 'r') as f:
    for line in f:
        line = line.strip()
        letter = line[0]
        state = line[1:]
        cache[state] = letter

debug("Cache2 inlezen...")
cache2 = defaultdict(dict)
with open("cache2", 'r') as f:
    for line in f:
        line = line.strip()
        letter,forbidden,template = line.split('|')
        cache2[template][forbidden] = letter
Example #9
0
import re
from galgje_utils import debug
import random as random_
choice = random_.Random().choice
del random_

debug("Woorden inlezen...")
all_words = []
with open('dutch', 'r') as f:
    for line in f:
        word = line.strip().lower()
        all_words.append(word)

def update_template(template, word, letter):
    res = ''
    for tc, wc in zip(template, word):
        if wc == letter:
            res += wc
        else:
            res += tc
    return res


class GalgjeState(object):
    def __init__(self):
        self.word = None
        self.template = None


class GalgjeError(Exception):
    pass
Example #10
0
from collections import defaultdict
from galgje import create_re_from_template, extract_letters_str, predict_outcome
from math import log as ln
import time

from galgje_utils import debug
from galgje_gamemaster import galgje as galgje_master
from galgje_gamemaster import galgje_guess
from galgje_gamemaster import GalgjeError

debug("Woorden inlezen...")
all_words = set()
all_words_by_word_length = defaultdict(set)
with open('dutch', 'rU') as f:
    for line in f:
        word = line.strip().lower()
        all_words.add(word)
        all_words_by_word_length[len(word)].add(word)

debug("Cache2 inlezen...")
cache2 = defaultdict(dict)
with open("cache2", 'rU') as f:
    for line in f:
        line = line.strip()
        letter,forbidden,template = line.split('|')
        cache2[template][forbidden] = letter


cache_hits = [0]
cache_misses = [0]
guesses = [0]