예제 #1
0
def main ():
    parser = optparse.OptionParser()
    parser.add_option("-l", "--list", action="store_true", dest="list", default=False, help="lists ole contents")
    parser.add_option("-x", "--extract", action="store_true", dest="extract", default=False, help="extract file")


    options, args = parser.parse_args()

    params = globals.Params()

    params.list =  options.list
    params.extract =  options.extract

    if len(args) < 1:
        globals.error("takes at least one arguments\n")
        parser.print_help()
        sys.exit(1)

    container =  OleContainer( args[ 0 ], params )

    if params.list == True:
        container.list() 
    if params.extract:
       files = args
       files.pop(0)
           
       for file in files:
           container.extract( file ) 
예제 #2
0
    def __check_args(self):
        if self.conflicts != Args.NOT_SPECIFIED and self.details == Args.NOT_SPECIFIED:
            error("--conflicts must be set with --details", RetVal.WRONG_ARGS)

        if self.search != Args.NOT_SPECIFIED:
            if self.details != Args.NOT_SPECIFIED or self.conflicts != Args.NOT_SPECIFIED:
                error("--search must be set alone", RetVal.WRONG_ARGS)
예제 #3
0
파일: wttr.py 프로젝트: nhadjarab/wttr.in
def get_moon(location, html=False, lang=None):
    date = None
    if '@' in location:
        date = location[location.index('@') + 1:]
        location = location[:location.index('@')]

    cmd = [PYPHOON]
    if date:
        try:
            dateutil.parser.parse(date)
        except:
            pass
        else:
            cmd += [date]

    env = os.environ.copy()
    if lang:
        env['LANG'] = lang
    print cmd
    p = Popen(cmd, stdout=PIPE, stderr=PIPE, env=env)
    stdout = p.communicate()[0]

    if html:
        p = Popen(["bash", ANSI2HTML, "--palette=solarized", "--bg=dark"],
                  stdin=PIPE,
                  stdout=PIPE,
                  stderr=PIPE)
        stdout, stderr = p.communicate(stdout)
        if p.returncode != 0:
            error(stdout + stderr)

    return stdout
예제 #4
0
 def openEditor(self,nfile):
     text = ""
     infile = open(nfile, 'r')
     tt = infile.read()
     try:
         text = str(tt)
         self.files.append(nfile)
         config.setFile(self.files) 
         self.dirty.append(False)
         tab = Editor(self,text,nfile) 
         self.tabWidget.addTab(tab,ospathbasename(nfile))
         #print len(self.files)
         tab.textChanged.connect(lambda:self.setDirty(nfile))  
         if(self.files != None):
             if(len(self.files)) != 0:
                 self.tabWidget.setCurrentIndex(len(self.files)-1)
     except:
         if(nfile in self.files):
             self.files.remove(nfile)
         config.setFile(self.files)
         QMessageBox.about(self,"Can't Open","File is Being Used\n"+nfile)
         error("Opening: File is Being Used "+nfile)
         return False
     finally:
         if(infile != None):
             infile.close() 
             return True
         return False
예제 #5
0
 def fileSave(self):
     if(self.files != None):
         if len(self.files) != 0:
             index = self.tabWidget.currentIndex()
             if not self.dirty[index]:
                 return
             fname = self.files[index]
             try:
                 fl = open(fname, 'w')
                 self.statusSaving()
                 self.progressStart()
                 if(config.encoding() == Encoding.UNICODE):
                     tempText = str(self.tabWidget.widget(index).text())
                     #tempText = codecs.encode(tempText,"utf-8")
                     fl.write(tempText)
                     fl.close()
                 else:
                     tempText = str(self.tabWidget.widget(index).text())
                     fl.write(tempText)
                     fl.close()
                 self.clearDirty(index)
             except:
                 QMessageBox.about(self, "Can't Save","File is Locked")
                 error("Saving:","File is Locked")
             self.statusWriting()
             self.progressStop()
             self.parser.run(self.files[index])
예제 #6
0
def html_wrapper(data):
    p = Popen([ "bash", ANSI2HTML, "--palette=xterm", "--bg=dark" ],  stdin=PIPE, stdout=PIPE, stderr=PIPE)
    data = data.encode('utf-8')
    stdout, stderr = p.communicate(data)
    if p.returncode != 0:
        error(stdout + stderr)
    return stdout.decode('utf-8')
예제 #7
0
def main ():
    parser = optparse.OptionParser()
    parser.add_option("-d", "--debug", action="store_true", dest="debug", default=False,
        help="Turn on debug mode")
    parser.add_option("--show-sector-chain", action="store_true", dest="show_sector_chain", default=False,
        help="Show sector chain information at the start of the output.")
    parser.add_option("--show-stream-pos", action="store_true", dest="show_stream_pos", default=False,
        help="Show the position of each record relative to the stream.")
    parser.add_option("--dump-mode", dest="dump_mode", default="flat", metavar="MODE",
        help="Specify the dump mode.  Possible values are: 'flat', 'xml', or 'canonical-xml'.  The default value is 'flat'.")
    options, args = parser.parse_args()
    params = globals.Params()
    params.debug = options.debug
    params.showSectorChain = options.show_sector_chain
    params.showStreamPos = options.show_stream_pos

    if len(args) < 1:
        globals.error("takes at least one argument\n")
        parser.print_help()
        sys.exit(1)

    dumper = XLDumper(args[0], params)
    if options.dump_mode == 'flat':
        dumper.dump()
    elif options.dump_mode == 'xml':
        dumper.dumpXML()
    elif options.dump_mode == 'canonical-xml' or options.dump_mode == 'cxml':
        dumper.dumpCanonicalXML()
    else:
        error("unknown dump mode: '%s'\n"%options.dump_mode)
        parser.print_help()
        sys.exit(1)
예제 #8
0
def _htmlize(ansi_output, title, parsed_query):
    """Return HTML representation of `ansi_output`.
    Use `title` as the title of the page.
    Format page according to query parameters from `parsed_query`."""

    cmd = ["bash", ANSI2HTML, "--palette=solarized"]
    if not parsed_query.get('inverted_colors'):
        cmd += ["--bg=dark"]

    proc = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
    stdout, stderr = proc.communicate(ansi_output.encode("utf-8"))
    stdout = stdout.decode("utf-8")
    stderr = stderr.decode("utf-8")
    if proc.returncode != 0:
        error(stdout + stderr)

    if parsed_query.get('inverted_colors'):
        stdout = stdout.replace(
            '<body class="">',
            '<body class="" style="background:white;color:#777777">')

    title = "<title>%s</title>" % title
    opengraph = _get_opengraph(parsed_query)
    stdout = re.sub("<head>", "<head>" + title + opengraph, stdout)
    return stdout
예제 #9
0
def main (args):
    exname, args = args[0], args[1:]
    if len(args) < 1:
        print("takes at least one argument")
        usage(exname)
        return

    params = globals.Params()
    try:
        opts, args = getopt.getopt(args, "h", ["help", "debug", "show-sector-chain"])
        for opt, arg in opts:
            if opt in ['-h', '--help']:
                usage(exname)
                return
            elif opt in ['--debug']:
                params.debug = True
            elif opt in ['--show-sector-chain']:
                params.showSectorChain = True
            else:
                error("unknown option %s\n"%opt)
                usage()

    except getopt.GetoptError:
        error("error parsing input options\n")
        usage(exname)
        return

    dumper = XLDumper(args[0], params)
    dumper.dump()
예제 #10
0
 def openAudio(self,nfile):
     if(ospathexists(nfile)):
         form = Audio(self,nfile)
         form.show()
         return True
     else:
         QMessageBox.about(self,"Can't Open","File Does Not Exist\n"+nfile)
         error("Opening: File Does Not Exist "+nfile)
         return False
예제 #11
0
def toColName(colID):
    if colID > 255:
        globals.error("Column ID greater than 255")
        raise InvalidCellAddress
    n1 = colID % 26
    n2 = int(colID / 26)
    name = struct.pack('b', n1 + ord('A'))
    if n2 > 0:
        name += struct.pack('b', n2 + ord('A'))
    return name
예제 #12
0
def toColName (colID):
    if colID > 255:
        globals.error("Column ID greater than 255")
        raise InvalidCellAddress
    n1 = colID % 26
    n2 = int(colID/26)
    name = struct.pack('b', n1 + ord('A'))
    if n2 > 0:
        name += struct.pack('b', n2 + ord('A'))
    return name
예제 #13
0
 def fillModel (self, model):
     pos, header, size, bytes, roflist = self.__readRecAndContBytes()
     handler = self.__getRecordHandler(header, size, bytes, roflist)
     if handler != None:
         try:
             handler.fillModel(model)
         except Exception as e:
             if not globals.params.catchExceptions:
                 raise
             globals.error("XLDirStream:fillModel: %s\n" % e)
     self.__postReadRecord(header)
예제 #14
0
 def __init__(self, header, bytes):
     self.header = header
     self.tokens = []
     try:
         # We are sometimes called with None bytes
         self.strm = globals.ByteStream(bytes)
     except:
         if not globals.params.catchExceptions:
             raise
         globals.error("FormulaParser: init called with None source\n")
         self.strm = globals.ByteStream("")
예제 #15
0
 def __init__(self, header, bytes):
     self.header = header
     self.tokens = []
     try:
         # We are sometimes called with None bytes
         self.strm = globals.ByteStream(bytes)
     except:
         if not globals.params.catchExceptions:
             raise
         globals.error("FormulaParser: init called with None source\n")
         self.strm = globals.ByteStream("")
예제 #16
0
def html_wrapper(data):
    """
    Convert ANSI text `data` to HTML
    """
    proc = Popen(
        ["bash", ANSI2HTML, "--palette=solarized", "--bg=dark"],
        stdin=PIPE, stdout=PIPE, stderr=PIPE)
    data = data.encode('utf-8')
    stdout, stderr = proc.communicate(data)
    if proc.returncode != 0:
        error(stdout + stderr)
    return stdout.decode('utf-8')
예제 #17
0
def parseCellAddress (bytes):
    if len(bytes) != 4:
        globals.error("Byte size is %d but expected 4 bytes for cell address.\n"%len(bytes))
        raise InvalidCellAddress

    row = globals.getSignedInt(bytes[0:2])
    col = globals.getSignedInt(bytes[2:4])
    colRelative = ((col & 0x4000) != 0)
    rowRelative = ((col & 0x8000) != 0)
    col = (col & 0x00FF)
    obj = CellAddress(col, row, colRelative, rowRelative)
    return obj
예제 #18
0
파일: html.py 프로젝트: yangweich/cheat.sh
 def _html_wrapper(data):
     """
     Convert ANSI text `data` to HTML
     """
     proc = Popen(
         ["bash", ANSI2HTML, "--palette=solarized", "--bg=dark"],
         stdin=PIPE, stdout=PIPE, stderr=PIPE)
     data = data.encode('utf-8')
     stdout, stderr = proc.communicate(data)
     if proc.returncode != 0:
         error(stdout + stderr)
     return stdout.decode('utf-8')
예제 #19
0
def parseCellAddress(bytes):
    if len(bytes) != 4:
        globals.error(
            "Byte size is %d but expected 4 bytes for cell address.\n" %
            len(bytes))
        raise InvalidCellAddress

    row = globals.getSignedInt(bytes[0:2])
    col = globals.getSignedInt(bytes[2:4])
    colRelative = ((col & 0x4000) != 0)
    rowRelative = ((col & 0x8000) != 0)
    col = (col & 0x00FF)
    obj = CellAddress(col, row, colRelative, rowRelative)
    return obj
예제 #20
0
def main():
    parser = optparse.OptionParser()
    parser.add_option("-d",
                      "--debug",
                      action="store_true",
                      dest="debug",
                      default=False,
                      help="Turn on debug mode")
    parser.add_option(
        "--show-sector-chain",
        action="store_true",
        dest="show_sector_chain",
        default=False,
        help="Show sector chain information at the start of the output.")
    parser.add_option(
        "--show-stream-pos",
        action="store_true",
        dest="show_stream_pos",
        default=False,
        help="Show the position of each record relative to the stream.")
    parser.add_option(
        "--dump-mode",
        dest="dump_mode",
        default="flat",
        metavar="MODE",
        help=
        "Specify the dump mode.  Possible values are: 'flat', 'xml', or 'canonical-xml'.  The default value is 'flat'."
    )
    options, args = parser.parse_args()
    params = globals.Params()
    params.debug = options.debug
    params.showSectorChain = options.show_sector_chain
    params.showStreamPos = options.show_stream_pos

    if len(args) < 1:
        globals.error("takes at least one argument\n")
        parser.print_help()
        sys.exit(1)

    dumper = XLDumper(args[0], params)
    if options.dump_mode == 'flat':
        dumper.dump()
    elif options.dump_mode == 'xml':
        dumper.dumpXML()
    elif options.dump_mode == 'canonical-xml' or options.dump_mode == 'cxml':
        dumper.dumpCanonicalXML()
    else:
        error("unknown dump mode: '%s'\n" % options.dump_mode)
        parser.print_help()
        sys.exit(1)
예제 #21
0
파일: html.py 프로젝트: yeliucn/cheat.sh
 def _html_wrapper(data):
     """
     Convert ANSI text `data` to HTML
     """
     cmd = ["bash", CONFIG['path.internal.ansi2html'], "--palette=solarized", "--bg=dark"]
     try:
         proc = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
     except FileNotFoundError:
         print("ERROR: %s" % cmd)
         raise
     data = data.encode('utf-8')
     stdout, stderr = proc.communicate(data)
     if proc.returncode != 0:
         error((stdout + stderr).decode('utf-8'))
     return stdout.decode('utf-8')
예제 #22
0
def get_moon(parsed_query):

    location = parsed_query['orig_location']
    html = parsed_query['html_output']
    lang = parsed_query['lang']
    hemisphere = parsed_query['hemisphere']

    date = None
    if '@' in location:
        date = location[location.index('@') + 1:]
        location = location[:location.index('@')]

    cmd = [globals.PYPHOON]
    if lang:
        cmd += ["-l", lang]

    if not hemisphere:
        cmd += ["-s", "south"]

    if date:
        try:
            dateutil.parser.parse(date)
        except Exception as e:
            print("ERROR: %s" % e)
        else:
            cmd += [date]

    p = Popen(cmd, stdout=PIPE, stderr=PIPE)
    stdout = p.communicate()[0]
    stdout = stdout.decode("utf-8")

    if parsed_query.get('no-terminal', False):
        stdout = globals.remove_ansi(stdout)

    if html:
        p = Popen(
            ["bash", globals.ANSI2HTML, "--palette=solarized", "--bg=dark"],
            stdin=PIPE,
            stdout=PIPE,
            stderr=PIPE)
        stdout, stderr = p.communicate(stdout.encode("utf-8"))
        stdout = stdout.decode("utf-8")
        stderr = stderr.decode("utf-8")
        if p.returncode != 0:
            globals.error(stdout + stderr)

    return stdout
예제 #23
0
 def createTab(self,nfile):
     if(nfile != None):
         if(self.files != None):
             if(len(self.files) != 0):
                     if(nfile in self.files):
                         #print "File Already Open\n"+nfile
                         self.tabWidget.setCurrentIndex(self.files.index(nfile))
                         return False
             if(ospathexists(nfile)):
                     self.openEditor(nfile)  
                     return True    
             else:
                 if(nfile in self.files):
                     self.files.remove(nfile)
                 config.setFile(self.files)
                 QMessageBox.about(self,"Can't Open","File Does Not Exist\n"+nfile)
                 error("Opening: File Does Not Exist "+nfile) 
                 return False
예제 #24
0
def main(args):
    exname, args = args[0], args[1:]
    if len(args) < 1:
        print("takes at least one argument")
        usage(exname)
        return

    params = globals.Params()
    try:
        opts, args = getopt.getopt(args, "h",
                                   ["help", "debug", "show-sector-chain"])
        for opt, arg in opts:
            if opt in ['-h', '--help']:
                usage(exname)
                return
            elif opt in ['--debug']:
                params.debug = True
            elif opt in ['--show-sector-chain']:
                params.showSectorChain = True
            else:
                error("unknown option %s\n" % opt)
                usage()

    except getopt.GetoptError:
        error("error parsing input options\n")
        usage(exname)
        return

    dumper = PPTDumper(args[0], params)
    if not dumper.dump():
        error("FAILURE\n")
예제 #25
0
 def fileSaveIndex(index):
         if not self.dirty[index]:
             return
         fname = self.files[index]
         try:
             fl = open(fname, 'w')
             self.statusSaving()
             self.progressStart()
             if(config.encoding() == Encoding.UNICODE):
                 tempText = str(self.tabWidget.widget(index).text())
                 #fl.write(tempText.encode("utf-8"))
                 fl.close()
             else:
                 tempText = str(self.tabWidget.widget(index).text())
                 fl.write(tempText)
                 fl.close()
             self.clearDirty(index)
             self.statusWriting()
             self.progressStop()
         except:
             QMessageBox.about(self, "Can't Save","File is Locked")
             error("Saving:","File is Locked "+fname)
예제 #26
0
    def createDOM(self, wb):
        nd = node.Element('worksheet')
        nd.setAttr('version', self.version)

        # cells
        rows = self.__rows.keys()
        rows.sort()
        for row in rows:
            rowNode = nd.appendElement('row')
            rowNode.setAttr('id', row)
            cols = self.__rows[row].keys()
            for col in cols:
                cell = self.__rows[row][col]
                cellNode = cell.createDOM(wb)
                rowNode.appendChild(cellNode)
                cellNode.setAttr('col', col)

        # table dimension
        if self.__firstDefinedCell != None:
            nd.setAttr('first-defined-cell', self.__firstDefinedCell.getName())

        if self.__firstFreeCell != None:
            try:
                nd.setAttr('first-free-cell', self.__firstFreeCell.getName())
            except Exception as e:
                if not globals.params.catchExceptions:
                    raise
                globals.error("createDOM: trying set firstFreeCell: %s\n" % e)
                pass

        self.__appendAutoFilterNode(wb, nd)  # autofilter (if exists)
        self.__appendHiddenRowsNode(wb, nd)  # hidden rows
        self.__appendRowHeightNode(wb, nd)  # row heights
        self.__appendShapesNode(wb, nd)  # drawing objects
        self.__appendCondFormatNode(wb, nd)  # conditional formatting
        self.__appendDataValidationNode(wb, nd)  # conditional formatting
        return nd
예제 #27
0
def main():
    parser = optparse.OptionParser()
    parser.add_option("-l",
                      "--list",
                      action="store_true",
                      dest="list",
                      default=False,
                      help="lists ole contents")
    parser.add_option("-x",
                      "--extract",
                      action="store_true",
                      dest="extract",
                      default=False,
                      help="extract file")

    options, args = parser.parse_args()

    params = globals.Params()

    params.list = options.list
    params.extract = options.extract

    if len(args) < 1:
        globals.error("takes at least one argument\n")
        parser.print_help()
        sys.exit(1)

    container = ole.OleContainer(args[0], params)

    if params.list == True:
        container.list()
    if params.extract:
        files = args
        files.pop(0)

        for file in files:
            container.extract(file)
예제 #28
0
def get_moon(location, html=False, lang=None, query=None):
    if query is None:
        query = {}

    date = None
    if '@' in location:
        date = location[location.index('@') + 1:]
        location = location[:location.index('@')]

    cmd = [PYPHOON]
    if date:
        try:
            dateutil.parser.parse(date)
        except Exception as e:
            print("ERROR: %s" % e)
        else:
            cmd += [date]

    env = os.environ.copy()
    if lang:
        env['LANG'] = lang
    p = Popen(cmd, stdout=PIPE, stderr=PIPE, env=env)
    stdout = p.communicate()[0]

    if query.get('no-terminal', False):
        stdout = remove_ansi(stdout)

    if html:
        p = Popen(["bash", ANSI2HTML, "--palette=solarized", "--bg=dark"],
                  stdin=PIPE,
                  stdout=PIPE,
                  stderr=PIPE)
        stdout, stderr = p.communicate(stdout)
        if p.returncode != 0:
            error(stdout + stderr)

    return stdout
예제 #29
0
    def createDOM (self, wb):
        nd = node.Element('worksheet')
        nd.setAttr('version', self.version)

        # cells
        rows = self.__rows.keys()
        rows.sort()
        for row in rows:
            rowNode = nd.appendElement('row')
            rowNode.setAttr('id', row)
            cols = self.__rows[row].keys()
            for col in cols:
                cell = self.__rows[row][col]
                cellNode = cell.createDOM(wb)
                rowNode.appendChild(cellNode)
                cellNode.setAttr('col', col)

        # table dimension
        if self.__firstDefinedCell != None:
            nd.setAttr('first-defined-cell', self.__firstDefinedCell.getName())

        if self.__firstFreeCell != None:
            try:
                nd.setAttr('first-free-cell', self.__firstFreeCell.getName())
            except Exception as e:
                if not globals.params.catchExceptions:
                    raise
                globals.error("createDOM: trying set firstFreeCell: %s\n" % e)
                pass

        self.__appendAutoFilterNode(wb, nd) # autofilter (if exists)
        self.__appendHiddenRowsNode(wb, nd) # hidden rows
        self.__appendRowHeightNode(wb, nd)  # row heights
        self.__appendShapesNode(wb, nd)     # drawing objects
        self.__appendCondFormatNode(wb, nd) # conditional formatting
        self.__appendDataValidationNode(wb, nd) # conditional formatting
        return nd
예제 #30
0
 def stop(self):
     QMessageBox.about(self,"Error",'Stopped / Net Connection Lost')
     error('Update: Stopped / Net Connection Lost')
예제 #31
0
 def timed(self):
     QMessageBox.about(self,"Error",'Connection Timed Out')
     error('Update: Timed out')
예제 #32
0
 def cant(self):
     QMessageBox.about(self,"Error",'File Cant be downloaded')
     error('Update: File Cant be downloaded')
예제 #33
0
 def net(self):
     QMessageBox.about(self,"Error",'Net Connection Not Found')
     error('Update: Net Connection Not Found')
예제 #34
0
 def retry(self):
     QMessageBox.about(self,"Error",'Cant Read repository Retry')
     error('Update: Cant Read repository Retry')
예제 #35
0
 def __readCompObjStream(self, dirstrm):
     try:
         strm = olestream.CompObjStream(dirstrm.bytes)
         strm.read()
     except olestream.CompObjStreamError:
         globals.error("failed to parse CompObj stream.\n")
예제 #36
0
 def __readCompObjStream (self, dirstrm):
     try:
         strm = olestream.CompObjStream(dirstrm.bytes)
         strm.read()
     except olestream.CompObjStreamError:
         globals.error("failed to parse CompObj stream.\n")
예제 #37
0
파일: wttr.py 프로젝트: nhadjarab/wttr.in
    def save_weather_data(location,
                          filename,
                          lang=None,
                          query=None,
                          location_name=None,
                          full_address=None):
        ansi_escape = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]')

        def remove_ansi(sometext):
            return ansi_escape.sub('', sometext)

        if _is_invalid_location(location):
            error("Invalid location: %s" % location)

        NOT_FOUND_MESSAGE_HEADER = ""
        while True:
            location_not_found = False
            if location in ["test-thunder"]:
                test_name = location[5:]
                test_file = TEST_FILE.replace('NAME', test_name)
                stdout = open(test_file, 'r').read()
                stderr = ""
                break
            print "LOCATION = ", location
            if location == NOT_FOUND_LOCATION:
                location_not_found = True
                location = DEFAULT_LOCATION

            cmd = [WEGO, '--city=%s' % location]

            if query.get('inverted_colors'):
                cmd += ['-inverse']

            if query.get('use_ms_for_wind'):
                cmd += ['-wind_in_ms']

            if query.get('narrow'):
                cmd += ['-narrow']

            if lang and lang in SUPPORTED_LANGS:
                cmd += ['-lang=%s' % lang]

            if query.get('use_imperial', False):
                cmd += ['-imperial']

            if location_name:
                cmd += ['-location_name', location_name]

            p = Popen(cmd, stdout=PIPE, stderr=PIPE)
            stdout, stderr = p.communicate()
            if p.returncode != 0:
                print "ERROR: location not found: %s" % location
                if 'Unable to find any matching weather location to the query submitted' in stderr:
                    if location != NOT_FOUND_LOCATION:
                        NOT_FOUND_MESSAGE_HEADER = u"ERROR: %s: %s\n---\n\n" % (
                            get_message('UNKNOWN_LOCATION', lang), location)
                        location = NOT_FOUND_LOCATION
                        continue
                error(stdout + stderr)
            break

        dirname = os.path.dirname(filename)
        if not os.path.exists(dirname):
            os.makedirs(dirname)

        if location_not_found:
            stdout += get_message('NOT_FOUND_MESSAGE', lang).encode('utf-8')
            stdout = NOT_FOUND_MESSAGE_HEADER.encode('utf-8') + stdout

        if 'days' in query:
            if query['days'] == '0':
                stdout = "\n".join(stdout.splitlines()[:7]) + "\n"
            if query['days'] == '1':
                stdout = "\n".join(stdout.splitlines()[:17]) + "\n"
            if query['days'] == '2':
                stdout = "\n".join(stdout.splitlines()[:27]) + "\n"

        first = stdout.splitlines()[0].decode('utf-8')
        rest = stdout.splitlines()[1:]
        if query.get('no-caption', False):

            separator = None
            if ':' in first:
                separator = ':'
            if u':' in first:
                separator = u':'

            if separator:
                first = first.split(separator, 1)[1]
                stdout = "\n".join([first.strip().encode('utf-8')] +
                                   rest) + "\n"

        if query.get('no-terminal', False):
            stdout = remove_ansi(stdout)

        if query.get('no-city', False):
            stdout = "\n".join(stdout.splitlines()[2:]) + "\n"

        if full_address and query.get('format', 'txt') != 'png':
            line = "%s: %s [%s]\n" % (get_message(
                'LOCATION',
                lang).encode('utf-8'), full_address.encode('utf-8'), location)
            stdout += line

        if query.get('padding', False):
            lines = [x.rstrip() for x in stdout.splitlines()]
            max_l = max(len(remove_ansi(x).decode('utf8')) for x in lines)
            last_line = " " * max_l + "   .\n"
            stdout = " \n" + "\n".join("  %s  " % x
                                       for x in lines) + "\n" + last_line

        open(filename, 'w').write(stdout)

        cmd = ["bash", ANSI2HTML, "--palette=solarized"]
        if not query.get('inverted_colors'):
            cmd += ["--bg=dark"]

        p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
        stdout, stderr = p.communicate(stdout)
        if p.returncode != 0:
            error(stdout + stderr)

        if query.get('inverted_colors'):
            stdout = stdout.replace(
                '<body class="">',
                '<body class="" style="background:white;color:#777777">')

        title = "<title>%s</title>" % first.encode('utf-8')
        opengraph = get_opengraph()
        stdout = re.sub("<head>", "<head>" + title + opengraph, stdout)
        open(filename + '.html', 'w').write(stdout)