Example #1
0
def train(fname):
    fr = codecs.open(fname, 'r', 'utf-8')
    data = []
    for i in fr:
        line = i.strip()
        if not line:
            continue
        tmp = map(lambda x: x.split('/'), line.split())
        data.append(tmp)
    fr.close()
    global tagger
    tagger = Tnt()
    tagger.train(data)
Example #2
0
 def __init__(self):
 	self._cheap_queue=dict()
     self.tnt = Tnt(self, 180)
     self.hl_list = self._readHilightList() or list()
     self.tnt.setThreadIdentifier(u'└─>')
     self.twitt_walker = TwittsWalker(self.tnt, self.hl_list) 
     self.twitter_scroll_box = urwid.ListBox(self.twitt_walker)
     self.info_bar = urwid.AttrWrap(urwid.Text(self.footer_text ),'foot')
     self.text_edit_area = urwid.AttrWrap(urwid.Edit(caption="[ 140]"), 'body')
     self.twitt_display_area = urwid.Frame(urwid.AttrWrap( self.twitter_scroll_box, 'body'), footer=self.info_bar)
     self.body=urwid.Pile([self.twitt_display_area,('flow',self.text_edit_area)])
Example #3
0
File: tty.py Project: aseba/TNT
class Tty(object):
    def __init__(self):
        self._sleeptime = 0
        self._loadConfig()
        while self.config["run"]:
            try:
                if self._sleeptime:
                    print(u"──> Trying to revive...")
                print(u"──> Starting Tnt Engine".encode("utf-8"))
                self.tnt = Tnt(self, 30)
                print(u"──> Starting Application".encode("utf-8"))
                self.main()
                self.tnt.run()
            except URLError:
                self._sleeptime += 10
                print(u"──> Uoops! connection problems, sleeping %s secs".encode("utf-8") % (self._sleeptime))
                sleep(self._sleeptime)
            except KeyboardInterrupt:
                print(u"──> Apllication killed".encode("utf-8"))
                self.config["run"] = False
            except Exception, bug:
                print(u"──> Uoops! System crashed: %s".encode("utf-8") % (bug))
Example #4
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import os
import codecs

from tnt import Tnt

data_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                         'resource/tag.marshal')
tagger = Tnt()
tagger.load(data_path)


def train(fname):
    fr = codecs.open(fname, 'r', 'utf-8')
    data = []
    for i in fr:
        line = i.strip()
        if not line:
            continue
        tmp = map(lambda x: x.split('/'), line.split())
        data.append(tmp)
    fr.close()
    global tagger
    tagger = Tnt()
    tagger.train(data)


def save(fname, iszip=True):
    tagger.save(fname, iszip)
Example #5
0
from sedex import Sedex
from tnt import Tnt
from frete_servico import FreteServico


class Frete:
    def __init__(self, empresa_que_fara_o_frete: FreteServico):
        self._empresa = empresa_que_fara_o_frete

    @property
    def empresa(self):
        return self._empresa

    @empresa.setter
    def empresa(self, empresa: FreteServico):
        self._empresa = empresa

    def calcular_valor(self, peso: float) -> float:
        return self._empresa.calcula(peso)


if __name__ == "__main__":
    frete = Frete(empresa_que_fara_o_frete=Sedex())
    resultado = frete.calcular_valor(10)
    print(resultado)

    frete.empresa = Tnt()
    resultado = frete.calcular_valor(10)
    print(resultado)
Example #6
0
 def __init__(self, name='other'):
     if name == 'tnt':
         self.segger = Tnt()
     else:
         self.segger = CharacterBasedGenerativeModel()
Example #7
0
class TwitterDisplay(object):
    palette = [
        ('body','light gray','black', 'standout'),
        ('foot','light gray', 'black', None),
        ('key','light cyan', 'black', 'underline'),
        ('title', 'white', 'black', None),
        ('nickname','light green','black', 'standout'),
        ('hour','light gray', 'black', None),
        ('twitnumber','light cyan', 'black', ),
        ('thread_indicator','dark red', 'black', 'standout'),
        ('text', 'white', 'black', None),
        ('text_mentioned','yellow','black', 'standout'),
        ('hilight', 'black', 'light gray', None),
        ('text_mine','light green','black', 'standout'),
        ]

        
    footer_text = [
        ('title', "TNT Urwid Frontend"), "    ",
        ('key', "UP"), ", ", ('key', "DOWN"), ", ",
        ('key', "PAGE UP"), " and ", ('key', "PAGE DOWN"),
        " move view  ",
        ('key', "Esc"), " exits",
        ]
    
    def __init__(self):
    	self._cheap_queue=dict()
        self.tnt = Tnt(self, 180)
        self.hl_list = self._readHilightList() or list()
        self.tnt.setThreadIdentifier(u'└─>')
        self.twitt_walker = TwittsWalker(self.tnt, self.hl_list) 
        self.twitter_scroll_box = urwid.ListBox(self.twitt_walker)
        self.info_bar = urwid.AttrWrap(urwid.Text(self.footer_text ),'foot')
        self.text_edit_area = urwid.AttrWrap(urwid.Edit(caption="[ 140]"), 'body')
        self.twitt_display_area = urwid.Frame(urwid.AttrWrap( self.twitter_scroll_box, 'body'), footer=self.info_bar)
        self.body=urwid.Pile([self.twitt_display_area,('flow',self.text_edit_area)])

    def main(self):
        self.ui = urwid.curses_display.Screen()
        self.ui.register_palette( self.palette )
        self.ui.run_wrapper( self.run )

    def updated(self, update_len):
        size = self.ui.get_cols_rows()
        self.twitt_walker.updated(update_len, size)
        canvas = self.body.render(size, focus=0)
        self.ui.draw_screen( size, canvas )
        
    def requestAuthPin(self, authURL):
        dialog = InputDialogDisplay("Please go to the following URL and authorize TNT for your account. \nPaste the resulting PIN Number in the textbox below and press enter. \n%s" % authURL, 0, 0)
        dialog.add_buttons([("Submit", 0)])
        return dialog.main()[1]

    def askIfSplit(self):
        return False

    def run(self):
        size = self.ui.get_cols_rows()
        urwid.set_encoding("utf-8")
        self.body.set_focus(1)
        while 1:
            self.body.set_focus(1)
            canvas = self.body.render(size, focus=True)
            self.ui.draw_screen( size, canvas )
            keys = None
            while not keys: 
                keys = self.ui.get_input()
            for k in keys:
                if k == 'window resize':
                    size = self.ui.get_cols_rows()
                    canvas = self.body.render(size, focus=True)
                    self.ui.draw_screen( size, canvas )
                elif k == 'esc':
                    self.do_quit()    
                elif k == 'enter':
                    self.commitText()
                elif ("up" in k) or ("down" in k):
                    self.body.set_focus(0)
                else:
                    self.body.set_focus(1)
                    #self.text_edit_area.keypress((1,), k) 
                    self.updatePrompt()
                self.body.keypress(size, k)
                self.body.set_focus(1)

                d_keys =  self._cheap_queue.keys() #not smart to iterate a dict and delete elements on the process
                for cheap_thread_key in d_keys:
                    if not self._cheap_queue[cheap_thread_key].isAlive():
                        self._cheap_queue[cheap_thread_key].join()
                        del(self._cheap_queue[cheap_thread_key])

                
    def commitText(self):
        text_to_send = self.text_edit_area.get_edit_text()
        temp_thread=Thread(target=self._process_command, args=(text_to_send,))
        self._cheap_queue[id(temp_thread)]=temp_thread
        self._cheap_queue[id(temp_thread)].start()
        #self._process_command(text_to_send)
        self.text_edit_area.set_edit_text("")
        self.updatePrompt()

    def updatePrompt(self):
        current_length = 140 - len(self.text_edit_area.get_edit_text())
        self.text_edit_area.set_caption("[ %03d] "% current_length)

    def lart(self, lart_title, lart_message=None):
        pass

    def _process_command(self, action):
        if action.startswith("/"):
            command_params = action.split(' ',1)
            command = command_params[0][1:].lower()
            params = ((len(command_params) > 1) and (command_params[1])) or None
            method = getattr(self, 'do_' + command, lambda x: None)
            method(params)
        elif len(action)>0:
            self.tnt.tweet(action)

    def _saveHilightList(self):
        file = open(TNT_PATH + 'hilights', 'w')
        pickle.dump(self.hl_list, file)
        file.close()

    def _readHilightList(self):
        done = False
        if(os.path.exists(TNT_PATH) and os.path.isfile(TNT_PATH + 'hilights')):
            file = open(TNT_PATH + 'hilights', 'r')
            hl = pickle.load(file)
            file.close()
            return hl
            
        
    #-- Actions --#    
    def _extract_params(self, params, message):
        split_message = message.split(' ', len(params)-1)
        param_dict = None
        if len(split_message) == len(params):
            param_dict = dict(zip(params, split_message))
        return param_dict


    def do_quit(self):
        sys.exit(0)
    do_q = do_quit

    def do_reply(self, message):
        args = self._extract_params(['id', 'message'], message)
        if args:
            replyingTo = self.tnt.getAuthorOf(args['id'])
            self.tnt.tweet('@%s %s' % (replyingTo, args['message']), args['id'])
        else:
            self.lart('reply')
    do_r = do_reply

    def do_dm(self, message):
        args = self._extract_params(['id', 'message'], message)
        if args and args['id'].startswith('@'):
            self.tnt.sendDirectMessage(args['id'], args['message'])
        else:
            self.lart('dm')

    def do_retweet(self, message):
        args = self._extract_params(['id'], message)
        if args:
            rtmessage = self.getMessage(args['id'])
            if(rtmessage):
                author = self.tnt.getAuthorOf(rtmessage.tid)
                text = 'RT @%s : %s' % (author, rtmessage.text)
                self.tnt.tweet(text)
            else:
                self.lart('retweet', "This message does not exist")
        else:
            self.lart('retweet')
    do_rt = do_retweet

    def do_hilight(self, message):
        args = self._extract_params(['id'], message)
        if args['id']:
            self.hl_list.append(args['id'].lower())
            self.twitt_walker.updated()
            self._saveHilightList()
    do_hl = do_hilight
    
    def do_unhilight(self, message):
        args = self._extract_params(['id'], message)
        if args['id'] and (args['id'].lower() in self.hl_list):
            self.hl_list.remove(args['id'].lower())
            self.twitt_walker.updated()
            self._saveHilightList()
    do_uhl = do_unhilight
    do_dehilight = do_unhilight


    def do_tweet(self, action):
        self.tnt.tweetWithCheck(action)