Ejemplo n.º 1
0
def process_single_scan_battery_keras(model_folder,
                                      source_scan_battery_dirname):
    # Make sure model_folder and source_scan_battery_dirname exist.
    if not os_path_isdir(model_folder):
        raise OSError('{}: model folder {} does not exist'.format(
            SCRIPT_FNAME, model_folder))
    if not os_path_isdir(source_scan_battery_dirname):
        raise OSError(
            '{}: source scan battery folder {} does not exist'.format(
                SCRIPT_FNAME, source_scan_battery_dirname))

    # model/scan_batteries folders.
    model_scan_batteries_dirname = os_path_join(model_folder,
                                                SCAN_BATTERIES_DIRNAME)
    model_scan_battery_dirname = os_path_join(
        model_scan_batteries_dirname,
        os_path_basename(source_scan_battery_dirname))

    # Copy source scan_batteries folder into model scan_batteries folder
    # TODO: Could also just copy the entire scan_batteries folder (all 3 types) into model_folder
    # logging_info('{}: copying {} to {}'.format(SCRIPT_FNAME, source_scan_battery_dirname, model_scan_battery_dirname))
    # copy_anything(source_scan_battery_dirname, model_scan_battery_dirname)
    # model_scan_battery_process_scripts_dirname = os_path_abspath(os_path_join(model_scan_battery_dirname, PROCESS_SCRIPTS_DIRNAME))

    # Grab all targets with glob
    mode_scan_battery_target_prefix = os_path_join(model_scan_battery_dirname,
                                                   TARGET_PREFIX + '*')
    target_dirnames = glob_glob(mode_scan_battery_target_prefix)
    if not target_dirnames:
        raise ValueError('{}: no targets found with prefix {}'.format(
            SCRIPT_FNAME, mode_scan_battery_target_prefix))

    for target_dirname in target_dirnames:
        process_single_target(target_dirname)

    # for target_dirname in target_dirnames:
    #     # print('{}: processing target directory {}'.format(SCRIPT_FNAME, target_dirname))
    #     process_single_target(target_dirname)

    # Remove scan battery-level folders
    for folder in SCAN_BATTERY_FOLDERS_TO_REMOVE:
        folder_path = os_path_join(model_scan_battery_dirname, folder)
        if os_path_isdir(folder_path):
            # print('{}: Trying to remove {}'.format(SCRIPT_FNAME, folder_path))
            try:
                shutil.rmtree(folder_path)
            except:
                raise OSError(
                    'Error: unable to remove file {}'.format(folder_path))

    # Remove scan battery-level files
    for file in SCAN_BATTERY_FILES_TO_REMOVE:
        file_path = os_path_join(model_scan_battery_dirname, file)
        if os_path_isfile(file_path):
            # print('{}: Trying to remove {}'.format(SCRIPT_FNAME, file_path))
            try:
                os_remove(file_path)
            except:
                raise OSError(
                    'Error: unable to remove file {}'.format(file_path))
Ejemplo n.º 2
0
 def __init__(self, session, path_left = None):
     if path_left is None:
         if os_path_isdir(config.plugins.RTiFileManager.path_left.value) and config.plugins.RTiFileManager.savedirs.value:
             path_left = config.plugins.RTiFileManager.path_left.value
         else:
             path_left = '/'
     
     if os_path_isdir(config.plugins.RTiFileManager.path_right.value) and config.plugins.RTiFileManager.savedirs.value:
         path_right = config.plugins.RTiFileManager.path_right.value
     else:
         path_right = '/'
     self.session = session
     Screen.__init__(self, session)
     self['list_left'] = FileList(path_left, matchingPattern = '^.*')
     self['list_right'] = FileList(path_right, matchingPattern = '^.*')
     self['red'] = Label(_('Delete'))
     self['green'] = Label(_('Attributes'))
     self['yellow'] = Label(_('Copy'))
     self['blue'] = Label(_('Rename'))
     self['actions'] = ActionMap([
         'ChannelSelectBaseActions',
         'WizardActions',
         'DirectionActions',
         'MenuActions',
         'NumberActions',
         'ColorActions'], {
         'ok': self.ok,
         'back': self.exit,
         'nextMarker': self.listRight,
         'prevMarker': self.listLeft,
         'up': self.goUp,
         'down': self.goDown,
         'left': self.goLeft,
         'right': self.goRight,
         'red': self.goRed,
         'green': self.goGreen,
         'yellow': self.goYellow,
         'blue': self.goBlue,
         '0': self.doRefresh,
         '1': self.doView,
         '2': self.doMKFile,
         '3': self.doMKDir }, -1)
     self.onLayoutFinish.append(self.listLeft)
     self['infoA'] = Label()
     self['infoB'] = Label()
     self['infoC'] = Label()
     self['infoD'] = Label()
     self.setTitle('RTi FileManager   v.1.0')
     self.strana = 1
     self.msgno = 0
     self.msgTimer = eTimer()
     self.msgTimer.callback.append(self.updateMsg)
     self.msgTimer.start(1000, True)
Ejemplo n.º 3
0
    def __init__(self, session, path_left=None):
        if path_left is None:
            if os_path_isdir(config.plugins.filebrowser.path_left.value
                             ) and config.plugins.filebrowser.savedirs.value:
                path_left = config.plugins.filebrowser.path_left.value
            else:
                path_left = "/"

        if os_path_isdir(config.plugins.filebrowser.path_right.value
                         ) and config.plugins.filebrowser.savedirs.value:
            path_right = config.plugins.filebrowser.path_right.value
        else:
            path_right = "/"

        self.session = session
        Screen.__init__(self, session)

        self["list_left"] = FileList(path_left, matchingPattern="^.*")
        self["list_right"] = FileList(path_right, matchingPattern="^.*")
        self["key_red"] = Label(_("Delete"))
        self["key_green"] = Label(_("Move"))
        self["key_yellow"] = Label(_("Copy"))
        self["key_blue"] = Label(_("Rename"))

        self["actions"] = ActionMap(
            [
                "ChannelSelectBaseActions", "WizardActions",
                "DirectionActions", "MenuActions", "NumberActions",
                "ColorActions", "ChannelSelectEPGActions"
            ], {
                "ok": self.ok,
                "back": self.exit,
                "menu": self.goMenu,
                "nextMarker": self.listRight,
                "prevMarker": self.listLeft,
                "nextBouquet": self.toggleList,
                "prevBouquet": self.toggleList,
                "up": self.goUp,
                "down": self.goDown,
                "left": self.goLeft,
                "right": self.goRight,
                "red": self.goRed,
                "green": self.goGreen,
                "yellow": self.goYellow,
                "blue": self.goBlue,
                "0": self.doRefresh,
                "info": self.displayItemInfo,
                "epg": self.displayItemInfo,
            }, -1)
        self.side = False
        self.onLayoutFinish.append(self.listLeft)
Ejemplo n.º 4
0
    def __init__(self, session, path_left=None):
        if path_left is None:
            if os_path_isdir(config.plugins.filebrowser.path_left.value
                             ) and config.plugins.filebrowser.savedirs.value:
                path_left = config.plugins.filebrowser.path_left.value
            else:
                path_left = "/"

        if os_path_isdir(config.plugins.filebrowser.path_right.value
                         ) and config.plugins.filebrowser.savedirs.value:
            path_right = config.plugins.filebrowser.path_right.value
        else:
            path_right = "/"

        self.session = session
        Screen.__init__(self, session)
        HelpableScreen.__init__(self)

        self["list_left"] = FileList(path_left, matchingPattern="^.*")
        self["list_right"] = FileList(path_right, matchingPattern="^.*")
        self["key_red"] = self["red"] = Label(_("Delete"))
        self["key_green"] = self["green"] = Label(_("Move"))
        self["key_yellow"] = self["yellow"] = Label(_("Copy"))
        self["key_blue"] = self["blue"] = Label(_("Rename"))
        self["key_menu"] = StaticText(_("MENU"))
        self["key_help"] = StaticText(_("HELP"))

        self["actions"] = HelpableActionMap(
            self, [
                "WizardActions", "DirectionActions", "MenuActions",
                "NumberActions", "ColorActions"
            ], {
                "ok": (self.ok, "Select item"),
                "back": (self.exit, "Exit"),
                "menu": (self.goMenu, "Open setup options"),
                "shiftDown": (self.listRight, "Select right list"),
                "shiftUp": (self.listLeft, "Select left list"),
                "up": (self.goUp, "Navigate up"),
                "down": (self.goDown, "Navigate down"),
                "left": (self.goLeft, "Page up"),
                "right": (self.goRight, "Page down"),
                "red": (self.goRed, "Delete"),
                "green": (self.goGreen, "Move"),
                "yellow": (self.goYellow, "Copy"),
                "blue": (self.goBlue, "Rename"),
                "0": (self.doRefresh, "Refresh"),
            },
            prio=-1,
            description=_("filebrowser buttons"))
        self.onLayoutFinish.append(self.listLeft)
Ejemplo n.º 5
0
def create_one_model_keras(models_dirname, model_type, model_version,
                           model_index):
    '''
    Args:
        models_dirname: str, the name of the directory containing
                        all neural network models. It's a short dirname
                        relative to the project root.
        model_type: str, denoting the type of the model. E.g. alexnet, mlp.
        model_version: int,
    Returns:
        dirpath: str. The dirpath of the created model directory.
    '''
    # 1. Come up with a new model name
    timestamp = datetime_datetime.now().strftime('%Y%m%d%H%M%S')
    model_dirname = '{}_v{}_{}_{}_created'.format(model_type, model_version,
                                                  timestamp, model_index)
    model_dirpath = os_path_join(models_dirname, model_dirname)
    if os_path_isdir(model_dirpath):
        raise OSError(
            '{}: model folder {} should not exist, but it does'.format(
                __name__, model_dirpath))

    # 2. Make that directory
    os_mkdir(model_dirpath)

    return model_dirpath
Ejemplo n.º 6
0
	def Info(self, dirsource):
		filename = dirsource.getFilename()
		sourceDir = dirsource.getCurrentDirectory() #self.SOURCELIST.getCurrentDirectory()
		mytest = dirsource.canDescent()
		if dirsource.canDescent():
			if dirsource.getSelectionIndex()!=0:
				if (not sourceDir) and (not filename):
					return pname
				else:
					sourceDir = filename
				if os_path_isdir(sourceDir):
					mode = os.stat(sourceDir).st_mode
				else:
					return ("")
				mode = oct(mode)
				curSelDir = sourceDir
				dir_stats = os_stat(curSelDir)
				dir_infos = "   " + _("Size") + str(self.Humanizer(dir_stats.st_size))+"    "
				dir_infos = dir_infos + _("Date") + " " + time_strftime("%d.%m.%Y - %H:%M:%S",time_localtime(dir_stats.st_mtime))+"    "
				dir_infos = dir_infos + _("Mode") + " " + str(mode[-3:])
				return (dir_infos)
			else:
				return ("")
		else:
			longname = sourceDir + filename
			if fileExists(longname):
				mode = os.stat(longname).st_mode
			else:
				return ("")
			mode = oct(mode)
			file_stats = os_stat(longname)
			file_infos = filename + "   " + _("Size") + " " + str(self.Humanizer(file_stats.st_size))+"    "
			file_infos = file_infos + _("Date") + " " + time_strftime("%d.%m.%Y - %H:%M:%S",time_localtime(file_stats.st_mtime))+"    "
			file_infos = file_infos + _("Mode") + " " + str(mode[-3:])
			return (file_infos)
Ejemplo n.º 7
0
 def load(self, url=None):
     tmpfile = ''.join((self.cachedir, quote_plus(url), '.jpg'))
     if os_path_isdir(self.cachedir) is False:
         print "cachedir not existing, creating it"
         os_mkdir(self.cachedir)
     if os_isfile(tmpfile):
         self.tmpfile = tmpfile
         self.onLoadFinished(None)
     elif url is not None:
         self.tmpfile = tmpfile
         head = {
             "Accept": "image/png,image/*;q=0.8,*/*;q=0.5",
             "Accept-Language": "de",
             "Accept-Encoding": "gzip,deflate",
             "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.7",
             "Keep-Alive": "300",
             "Referer": "http://maps.google.de/",
             "Cookie:":
             "khcookie=fzwq1BaIQeBvxLjHsDGOezbBcCBU1T_t0oZKpA; PREF=ID=a9eb9d6fbca69f5f:TM=1219251671:LM=1219251671:S=daYFLkncM3cSOKsF; NID=15=ADVC1mqIWQWyJ0Wz655SirSOMG6pXP2ocdXwdfBZX56SgYaDXNNySnaOav-6_lE8G37iWaD7aBFza-gsX-kujQeH_8WTelqP9PpaEg0A_vZ9G7r50tzRBAZ-8GUwnEfl",
             "Connection": "keep-alive"
         }
         agt = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.2) Gecko/2008091620 Firefox/3.0.2"
         downloadPage(url, self.tmpfile, headers=head,
                      agent=agt).addCallback(
                          self.onLoadFinished).addErrback(self.onLoadFailed)
     elif self.default:
         self.picload.startDecode(self.default)
Ejemplo n.º 8
0
	def Info(self, dirsource):
		filename = dirsource.getFilename()
		sourceDir = dirsource.getCurrentDirectory() #self.SOURCELIST.getCurrentDirectory()
		mytest = dirsource.canDescent()
		if dirsource.canDescent():
			if dirsource.getSelectionIndex()!=0:
				if (not sourceDir) and (not filename):
					return pname
				else:
					sourceDir = filename
				if os_path_isdir(sourceDir):
					mode = os.stat(sourceDir).st_mode
				else:
					return ("")
				mode = oct(mode)
				curSelDir = sourceDir
				dir_stats = os_stat(curSelDir)
				dir_infos = "   " + _("Size") + str(self.Humanizer(dir_stats.st_size))+"    "
				dir_infos = dir_infos + _("Date") + " " + time_strftime("%d.%m.%Y - %H:%M:%S",time_localtime(dir_stats.st_mtime))+"    "
				dir_infos = dir_infos + _("Mode") + " " + str(mode[-3:])
				return (dir_infos)
			else:
				return ("")
		else:
			longname = sourceDir + filename
			if fileExists(longname):
				mode = os.stat(longname).st_mode
			else:
				return ("")
			mode = oct(mode)
			file_stats = os_stat(longname)
			file_infos = filename + "   " + _("Size") + " " + str(self.Humanizer(file_stats.st_size))+"    "
			file_infos = file_infos + _("Date") + " " + time_strftime("%d.%m.%Y - %H:%M:%S",time_localtime(file_stats.st_mtime))+"    "
			file_infos = file_infos + _("Mode") + " " + str(mode[-3:])
			return (file_infos)
Ejemplo n.º 9
0
def r2_dnn_stft(target_dirname, saving_to_disk=False):
    LOGGER.info(
        '{}: r2: Generating old_stft from chandat'.format(target_dirname))
    assert os_path_isdir(target_dirname)
    chandat_obj = loadmat(os_path_join(target_dirname, CHANDAT_FNAME))
    chandat = chandat_obj['chandat']
    y, num_elements, num_beams = chandat.shape  # y is depth

    # Take STFT of the channel data for specified A-line
    chandat_stft = stft(chandat, LEN_EACH_SECTION, FRAC_OVERLAP, PADDING)
    chandat_stft['origSigSize'] = [y, num_elements, num_beams]

    chandat_stft['stft'] = chandat_stft['stft'].permute(
        3, 2, 1, 0, 4
    )  # should be num_beams, num_elements, num_frames, num_frequencies, real_imag
    chandat_obj = {
        'old_stft_real': chandat_stft['stft'][:, :, :, :, 0],
        'old_stft_imag': chandat_stft['stft'][:, :, :, :, 1],
    }

    if saving_to_disk is True:
        savemat(os_path_join(target_dirname, OLD_STFT_SAVE_FNAME), chandat_obj)

    LOGGER.info('{}: r2: Done'.format(target_dirname))
    return chandat_obj
Ejemplo n.º 10
0
 def goRed(self):
     for file in self.selectedFiles:
         if os_path_isdir(file):
             container = eConsoleAppContainer()
             container.execute("rm -rf '%s'" % file)
         else:
             remove(file)
     self.exit()
Ejemplo n.º 11
0
	def goRed(self):
		for file in self.selectedFiles:
			if os_path_isdir(file):
				container = eConsoleAppContainer()
				container.execute("rm -rf '%s'" % file)
			else:
				remove(file)
		self.exit()
Ejemplo n.º 12
0
def r4_dnn_istft(target_dirname,
                 chandat_obj=None,
                 new_stft_object=None,
                 is_saving_chandat_dnn=True):
    LOGGER.info(
        '{}: r4: Doing istft on denoised stft...'.format(target_dirname))
    assert os_path_isdir(target_dirname)
    if chandat_obj is None:
        chandat_obj = loadmat(os_path_join(target_dirname, CHANDAT_FNAME))
    chandat_data = chandat_obj['chandat']
    num_rows, num_elements, num_beams = chandat_data.shape
    beam_position_x = chandat_obj['beam_position_x']
    if 'depth' in chandat_obj:
        depth = chandat_obj['depth']
    else:
        depth = chandat_obj['t'] / chandat_obj['fs'] * chandat_obj['c'] / 2
    f0 = chandat_obj['f0']

    del chandat_obj

    if new_stft_object is None:
        new_stft_object = loadmat(os_path_join(target_dirname, NEW_STFT_FNAME))
    new_stft = torch_stack(
        (torch_from_numpy(new_stft_object['new_stft_real']),
         torch_from_numpy(new_stft_object['new_stft_imag'])),
        axis=-1)
    # new_stft = new_stft_real + 1j*new_stft_imag

    del new_stft_object

    chandat_stft = stft(
        torch_zeros(num_rows, num_elements, num_beams, dtype=torch_float64),
        LEN_EACH_SECTION, FRAC_OVERLAP, PADDING)
    chandat_stft['origSigSize'] = [num_rows, num_elements, num_beams]

    # create new and old stfts
    # chandat_stft_new = copy(chandat_stft)
    # chandat_stft_new['stft'] = new_stft
    chandat_stft['stft'] = new_stft
    chandat_new = istft(chandat_stft)
    # chandat_new = non_iter_ls_inv_stft(chandat_stft)
    # what = istft(chandat_stft, N, window=window, hop_length=2, center=False, onesided=False, normalized=False, pad_mode='constant', length=y)

    chandat_new[-3:-1, :, :] = 0

    chandat_dnn_object = {
        'chandat_dnn': chandat_new,
        'beam_position_x': beam_position_x,
        'depth': depth,
        'f0': f0,
    }

    if is_saving_chandat_dnn is True:
        savemat(os_path_join(target_dirname, CHANDAT_DNN_SAVE_FNAME),
                chandat_dnn_object)

    LOGGER.info('{}: r4: Done'.format(target_dirname))
    return chandat_dnn_object
Ejemplo n.º 13
0
    def __init__(self, session,path_left=None):
        if path_left is None:
            if os_path_isdir(config.plugins.filebrowser.path_left.value) and config.plugins.filebrowser.savedirs.value:
                path_left = config.plugins.filebrowser.path_left.value
            else:
                path_left = "/"

        if os_path_isdir(config.plugins.filebrowser.path_right.value) and config.plugins.filebrowser.savedirs.value:
            path_right = config.plugins.filebrowser.path_right.value
        else:
            path_right = "/"

        self.session = session
        Screen.__init__(self, session)

        self["list_left"] = FileList(path_left, matchingPattern = "^.*")
        self["list_right"] = FileList(path_right, matchingPattern = "^.*")
        self["key_red"] = Label(_("Delete"))
        self["key_green"] = Label(_("Move"))
        self["key_yellow"] = Label(_("Copy"))
        self["key_blue"] = Label(_("Rename"))


        self["actions"] = ActionMap(["ChannelSelectBaseActions","WizardActions", "DirectionActions","MenuActions","NumberActions","ColorActions"],
            {
             "ok":      self.ok,
             "back":    self.exit,
             "menu":    self.goMenu,
             "nextMarker": self.listRight,
             "prevMarker": self.listLeft,
             "nextBouquet": self.listRight,
             "prevBouquet": self.listLeft,
             "up": self.goUp,
             "down": self.goDown,
             "left": self.goLeft,
             "right": self.goRight,
             "red": self.goRed,
             "green": self.goGreen,
             "yellow": self.goYellow,
             "blue": self.goBlue,
             "0": self.doRefresh,
             }, -1)
        self.onLayoutFinish.append(self.listLeft)
Ejemplo n.º 14
0
 def goRed(self):
     filename = self.SOURCELIST.getFilename()
     if not filename:
         return
     sourceDir = self.SOURCELIST.getCurrentDirectory()
     if os_path_isdir(filename):
         txt = _("Delete directory") + "?\n\n%s" % (filename)
     else:
         txt =_("Delete file") + "?\n\n%s\n%s\n%s" % (filename,_("from dir"),sourceDir)
     self.session.openWithCallback(self.doDelete, MessageBox, txt, type=MessageBox.TYPE_YESNO, default=False, simple=True)
Ejemplo n.º 15
0
def get_req_file(path):
    '''Return `requirements.txt` or `reqs.txt` file if exists'''
    req_file = False
    if os_path_isdir(path):
        files = os_listdir(path)
        filtered = [x for x in files if x in REQS_FILES]
        if filtered:
            req_file = os_path_join(path, next(x for x in filtered))
        else:
            req_file = False
    return req_file
Ejemplo n.º 16
0
 def doRename(self, newname = None):
     if newname:
         filename = self.SOURCELIST.getFilename()
         sourceDir = self.SOURCELIST.getCurrentDirectory()
         if os_path_isdir(filename):
             txt = _("renaming directory ...")
             cmd = ["mv \""+filename+"\" \""+sourceDir+newname+"\""]
         else:
             txt = _("renaming file ...")
             cmd = ["mv \""+sourceDir+filename+"\" \""+sourceDir+newname+"\""]
         self.session.openWithCallback(self.doRenameCB, Console, title = txt, cmdlist = cmd, closeOnSuccess = True)
Ejemplo n.º 17
0
 def goBlue(self):
     filename = self.SOURCELIST.getFilename()
     if not filename:
         return
     sourceDir = self.SOURCELIST.getCurrentDirectory()
     if os_path_isdir(filename):
         text = _("Rename directory")
         filename = os_path_basename(os_path_dirname(filename))
     else:
         text = _("Rename file")
     self.session.openWithCallback(self.doRename, VirtualKeyBoard, title = text, text = filename)
Ejemplo n.º 18
0
 def goGreen(self):
     filename = self.SOURCELIST.getFilename()
     if not filename:
         return
     sourceDir = self.SOURCELIST.getCurrentDirectory()
     targetDir = self.TARGETLIST.getCurrentDirectory()
     if os_path_isdir(filename):
         txt = _("Move directory") + "?\n\n%s\n%s\n%s" % (filename,_("to"),targetDir)
     else:
         txt = _("Move file") + "?\n\n%s\n%s\n%s\n%s\n%s" % (filename,_("from dir"),sourceDir,_("to dir"),targetDir)
     self.session.openWithCallback(self.doMove, MessageBox, txt, type=MessageBox.TYPE_YESNO, default=True, simple=True)
Ejemplo n.º 19
0
 def doDelete(self,result = False):
     if result:
         filename = self.SOURCELIST.getFilename()
         sourceDir = self.SOURCELIST.getCurrentDirectory()
         if os_path_isdir(filename):
             txt = _("deleting directory ...")
             cmd = ["rm -r \""+filename+"\""]
         else:
             txt = _("deleting file ...")
             cmd = ["rm \""+sourceDir+filename+"\""]
         self.session.openWithCallback(self.doDeleteCB, Console, title = txt, cmdlist = cmd, closeOnSuccess = True)
Ejemplo n.º 20
0
 def doMove(self, result = True):
     if result:
         filename = self.SOURCELIST.getFilename()
         sourceDir = self.SOURCELIST.getCurrentDirectory()
         targetDir = self.TARGETLIST.getCurrentDirectory()
         if os_path_isdir(filename):
             txt = _("moving directory, wait please ...")
             cmd = ["mv \""+filename+"\" \""+targetDir+"\""]
         else:
             txt = _("moving file ...")
             cmd = ["mv \""+sourceDir+filename+"\" \""+targetDir+"\""]
         self.session.openWithCallback(self.doMoveCB,Console, title = txt, cmdlist = cmd, closeOnSuccess = True)
def stitch(args):
    global min_match
    type_ = args.type
    source = args.source
    min_match = args.minmatch or 500
    min_match = int(min_match)
    if type_ == "video":
        if os_path_isdir(source):
            print("Source is not a video.")
            exit(-1)
        loadFramesFromVideo(source, args.reverse)
        _stitch_video(args.direction)
    elif type_ == "frames":
        if not os_path_isdir(source):
            print("Source is not a folder.")
            exit(-1)
        loadFramesFromFrames(source)
        _stitch_frames(args.direction)
    else:
        print(f"Unknown type {type_}")
        exit(-1)
Ejemplo n.º 22
0
 def displayItemInfo(self):
     filename = self.SOURCELIST.getFilename()
     if not filename:
         return
     if os_path_isdir(filename):
         curFile = os_stat(filename)
         if filename != '/':
             filename = filename.rstrip('/')
         fileinfo = ("%s        " % self.dirSize(filename) if config.plugins.filebrowser.dir_size.value else "") + self.fileTime(curFile.st_mtime)
     else:
         curFile = os_stat(self.SOURCELIST.getCurrentDirectory() + filename)
         fileinfo = "%s  (%s)        %s" % (self.humanizer(curFile.st_size),'{:,.0f}'.format(curFile.st_size), self.fileTime(curFile.st_mtime))
     self.session.open(FilebrowserScreenInfo, (filename, fileinfo))
Ejemplo n.º 23
0
def is_module(path):
    '''return False if the path doesn't contain an odoo module, and the full
    path to the module manifest otherwise'''

    if not os_path_isdir(path):
        return False
    files = os_listdir(path)
    filtered = [x for x in files if x in (MANIFEST_FILES + ['__init__.py'])]
    if len(filtered) == 2 and '__init__.py' in filtered:
        return os_path_join(path,
                            next(x for x in filtered if x != '__init__.py'))
    else:
        return False
Ejemplo n.º 24
0
 def load(self, url = None):
     tmpfile = ''.join((self.cachedir, quote_plus(url), ''))
     if os_path_isdir(self.cachedir) is False:
         print "cachedir not existing, creating it"
         os_mkdir(self.cachedir)
     if os_isfile(tmpfile):
         self.tmpfile = tmpfile
         self.onLoadFinished(None)
     elif url is not None:
         self.tmpfile = tmpfile
         head = { }
         agt = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.2) Gecko/2008091620 Firefox/3.0.2"
         downloadPage(url,self.tmpfile,headers=head,agent=agt).addCallback(self.onLoadFinished).addErrback(self.onLoadFailed)
     elif self.default:
         self.picload.startDecode(self.default)
Ejemplo n.º 25
0
 def load(self, url=None):
     tmpfile = ''.join((self.cachedir, quote_plus(url), ''))
     if os_path_isdir(self.cachedir) is False:
         print "cachedir not existing, creating it"
         os_mkdir(self.cachedir)
     if os_isfile(tmpfile):
         self.tmpfile = tmpfile
         self.onLoadFinished(None)
     elif url is not None:
         self.tmpfile = tmpfile
         head = {}
         agt = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.2) Gecko/2008091620 Firefox/3.0.2"
         downloadPage(url, self.tmpfile, headers=head, agent=agt).addCallback(self.onLoadFinished).addErrback(self.onLoadFailed)
     elif self.default:
         self.picload.startDecode(self.default)
Ejemplo n.º 26
0
def get_addons_paths(root_path):
    addons_paths = []
    try:
        filenames = os_listdir(root_path)
    except OSError as os_err:
        if os_err.errno == errno.ENOENT:
            filenames = []
    for filename in filenames:
        path = os_path_join(root_path, filename)
        if os_path_isdir(path):
            if is_module(path):
                addons_paths.append(path)
            else:
                addons_paths += get_addons_paths(path)
        else:
            pass
    return addons_paths
Ejemplo n.º 27
0
 def update_document_in_path(self):
     filename = 'CVN-%s-%s.pdf' % (
         self.user_profile.documento,
         self.uploaded_at.strftime('%Y-%m-%d-%Hh%Mm%Ss'))
     relative_pdf_path = get_old_cvn_path(self, filename)
     full_pdf_path = os_path_join(st.MEDIA_ROOT, relative_pdf_path)
     if self.cvn_file.path != full_pdf_path:
         root_path = '/'.join(full_pdf_path.split('/')[:-1])
         if not os_path_isdir(root_path):
             makedirs(root_path)
         # This just moves the file from the old path to the new one,
         file_move_safe(self.cvn_file.path,
                        full_pdf_path,
                        allow_overwrite=True)
         # so is therefore necessary to update the name with the new
         # relative path before saving the model
         self.cvn_file.name = relative_pdf_path
         self.save()
Ejemplo n.º 28
0
def init_directory(bad_urls_dir, tei_logger):
    """Initialise bad_urls_dir:
       1. Resolve path (absolute or relative to the working directory)
       2. Check if not exists and create it (warn if exists)
       3. Check if bad_urls_dir is a directory (fail gracefully if it is other than directory)
       4. Check if bad_urls_dir empty (warn if not)
    """
    if not os_path_isabs(bad_urls_dir):
        bad_urls_dir = os_path_join(os_path_abspath(getcwd()), bad_urls_dir)
    if os_path_exists(bad_urls_dir):
        tei_logger.log('WARNING', f'{bad_urls_dir} exists!')
    else:
        makedirs(bad_urls_dir, exist_ok=True)
    if not os_path_isdir(bad_urls_dir):
        tei_logger.log('CRITICAL', f'{bad_urls_dir} is not a directory!')
        exit(1)
    if len(listdir(bad_urls_dir)) > 0:
        tei_logger.log('WARNING', f'{bad_urls_dir} is not empty!')
    return bad_urls_dir
Ejemplo n.º 29
0
 def update_document_in_path(self):
     # Latest CVN
     relative_pdf_path = get_cvn_path(self, u'fake.pdf')
     full_pdf_path = os_path_join(st.MEDIA_ROOT, relative_pdf_path)
     xml_path = get_cvn_path(self, u'fake.xml')
     full_xml_path = os_path_join(st.MEDIA_ROOT, xml_path)
     root_path = '/'.join(full_pdf_path.split('/')[:-1])
     if not os_path_isdir(root_path):
         makedirs(root_path)
     if self.cvn_file.path != full_pdf_path:
         file_move_safe(self.cvn_file.path,
                        full_pdf_path,
                        allow_overwrite=True)
         self.cvn_file.name = relative_pdf_path
     if self.xml_file.path != full_xml_path:
         file_move_safe(self.xml_file.path,
                        full_xml_path,
                        allow_overwrite=True)
         self.xml_file.name = xml_path
     self.save()
Ejemplo n.º 30
0
	def load(self, url = None):
		if url is None:
			self.instance.setPixmap(None)
			return
		url = isinstance(url,unicode) and url.encode('utf-8') or url
		if os_isfile(url):
			self.tmpfile = url
			self.onLoadFinished(None)
			return
		tmpfile = ''.join((self.cachedir, quote_plus(url), '.jpg'))
		if os_path_isdir(self.cachedir) is False:
			print "cachedir not existing, creating it"
			os_mkdir(self.cachedir)
		if os_isfile(tmpfile):
			self.tmpfile = tmpfile
			self.onLoadFinished(None)
		elif url is not None:
			self.tmpfile = tmpfile
			agt = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.2) Gecko/2008091620 Firefox/3.0.2"
			downloadPage(url,self.tmpfile, agent=agt).addCallback(self.onLoadFinished).addErrback(self.onLoadFailed)
		elif self.default:
			self.picload.startDecode(self.default)
Ejemplo n.º 31
0
def main(main_path, ext_path, result_path):
    def unique(seq):
        seen = set()
        seen_add = seen.add
        return [x for x in seq if not (x in seen or seen_add(x))]

    print('MAIN_ADDONS_PATH:', main_path)
    print('EXT_ADDONS_PATH:', ext_path)
    print('RESULT_EXT_ADDONS_PATH:', result_path)
    if not os_path_isdir(result_path):
        os.makedirs(result_path)
    main_addons = parse_with_depends(get_addons_paths(main_path))
    main_deps = [data['depends'] for name, data in main_addons.iteritems()]
    main_deps = unique([item for sublist in main_deps for item in sublist])
    main_deps.sort()
    ext_addons = parse_with_depends(get_addons_paths(ext_path))

    need_link = ext_addons
    for addon_name, row in need_link.iteritems():
        src = row['path']
        dst = os_path_join(result_path, addon_name)
        if not os.path.islink(dst):
            os.symlink(src, dst)
        print('{} -> {}'.format(src, dst))
Ejemplo n.º 32
0
	def load(self, url = None):
		tmpfile = ''.join((self.cachedir, quote_plus(url), '.jpg'))
		if os_path_isdir(self.cachedir) is False:
			print "cachedir not existing, creating it"
			os_mkdir(self.cachedir)
		if os_isfile(tmpfile):
			self.tmpfile = tmpfile
			self.onLoadFinished(None)
		elif url is not None:
			self.tmpfile = tmpfile
			head = {
				"Accept":"image/png,image/*;q=0.8,*/*;q=0.5",
				"Accept-Language":"de",
				"Accept-Encoding":"gzip,deflate",
				"Accept-Charset":"ISO-8859-1,utf-8;q=0.7,*;q=0.7",
				"Keep-Alive":"300",
				"Referer":"http://maps.google.de/",
				"Cookie:": "khcookie=fzwq1BaIQeBvxLjHsDGOezbBcCBU1T_t0oZKpA; PREF=ID=a9eb9d6fbca69f5f:TM=1219251671:LM=1219251671:S=daYFLkncM3cSOKsF; NID=15=ADVC1mqIWQWyJ0Wz655SirSOMG6pXP2ocdXwdfBZX56SgYaDXNNySnaOav-6_lE8G37iWaD7aBFza-gsX-kujQeH_8WTelqP9PpaEg0A_vZ9G7r50tzRBAZ-8GUwnEfl",
				"Connection":"keep-alive"
			}
			agt = "Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.0.2) Gecko/2008091620 Firefox/3.0.2"
			downloadPage(url,self.tmpfile,headers=head,agent=agt).addCallback(self.onLoadFinished).addErrback(self.onLoadFailed)
		elif self.default:
			self.picload.startDecode(self.default)
Ejemplo n.º 33
0
def _build(sources, outfolder, gentoc, toc, external_css):
    for pagename, source in sources.items():
        # If there is no valid source
        if source is None:
            continue
        # Clear soup and add en empty, new body
        SOUP.body.decompose()
        new(SOUP.html, 'body')

        # Set title
        SOUP.html.head.title.string = pagename
        # Get essentail values
        filename, depends = toc[pagename]
        # Constants
        SECTIONS = 7
        # Build basic structure
        column1 = new(SOUP.body, 'div', id='column1')
        column2 = new(SOUP.body, 'div', id='column2')

        generic = new(column1, 'div', id='generic')
        sidebar = new(column1, 'div', id='sidebar')
        content = new(column2, 'div', id='content')

        # OPTIONAL: custom header section
        try:
            _html_format(generic, source['HEAD'], outfolder)
            new(generic, 'br')
        except KeyError:
            SECTIONS -= 1
        # OPTIONAL: custom menu in sidebar
        try:
            _html_format(sidebar, source['MENU'], outfolder)
            new(sidebar, 'br')
        except KeyError:
            SECTIONS -= 1
        # OPTIONAL: custom abstract and introduction
        try:
            _html_format(content, source['INFO'], outfolder)
            new(content, 'br')
        except KeyError:
            SECTIONS -= 1
        # OPTIONAL: index
        if gentoc:
            sidebar_type = new(sidebar, 'div')
            new(sidebar_type, 'p', class_='label', string='Modules:')
            new(sidebar, 'br')
            _indx_format(sidebar, pagename, toc)
            new(sidebar, 'br')

        # TODO: Implement a Schema validator for better user-feedback

        # TODO: add FOOT key

        # TODO: add EXEC to cdoc to add "interactive" python snippets to code
        # EXEC: |
        #   with open('VERSION') as file:
        #       # Insert to USER:About
        #       DOC[USER][0].insert(0, {'name': 'Version', 'info': file.read()})

        # OPTIONAL: text and code
        try:
            blocks = source['TEXT']
            for block in blocks:
                # Get the first element of the list as the section name
                try:
                    section = string_capwords(block[0])
                except IndexError:
                    continue
                sidebar_text = new(sidebar, 'div')
                new(sidebar_text, 'p', class_='label',
                                       string='{}:'.format(section))
                new(sidebar_text, 'br')
                content_text = new(content, 'div')
                new(content_text, 'h2', class_='title', string=section)
                for user in block[1:]:
                    _text_format(sidebar_text, content_text, user)
                new(sidebar, 'br')
        except KeyError:
            SECTIONS -= 1
        # OPTIONAL: user defined
        try:
            userdefs = source['USER']
            for userdef in userdefs:
                # Get the first element of the list as the section name
                try:
                    section = string_capwords(userdef[0])
                except IndexError:
                    continue
                sidebar_user = new(sidebar, 'div')
                new(sidebar_user, 'p', class_='label',
                                       string='{}:'.format(section))
                new(sidebar_user, 'br')
                content_user = new(content, 'div')
                new(content_user, 'h2', class_='title', string=section)
                for user in userdef[1:]:
                    _user_format(sidebar_user, content_user, user)
                new(sidebar, 'br')
        except KeyError:
            SECTIONS -= 1
        # OPTIONAL: type definitions
        try:
            types = source['TYPE']
            sidebar_type = new(sidebar, 'div')
            new(sidebar_type, 'p', class_='label', string='Types:')
            new(sidebar_type, 'br')
            content_type = new(content, 'div')
            new(content_type, 'h2', class_='title', string='Types')
            for type in types:
                _type_format(sidebar_type, content_type, type)
            new(sidebar, 'br')
        except KeyError:
            SECTIONS -= 1
        # OPTIONAL: function definitions
        try:
            funcs = source['FUNC']
            sidebar_func = new(sidebar, 'div')
            new(sidebar_func, 'p', class_='label', string='Functions:')
            new(sidebar_func, 'br')
            content_func = new(content, 'div')
            new(content_func, 'h2', class_='title', string='Functions')
            for func in funcs:
                _func_format(sidebar_func, content_func, func)
        except KeyError:
            SECTIONS -= 1

        # Create HTML file
        if SECTIONS:
            output = os_path_join(outfolder, filename)
            with open(output, 'w', encoding='utf-8') as file:
                file.write(SOUP.decode(formatter='html'))
                print('CDOC: {!r} processed'.format(output))
            continue
        print('CDOC: !!! WARNING !!! in {!r} no data provided'.format(pagename))
    # Create folder if not exists to css
    stylepath = os_path_join(outfolder, 'css')
    try:
        os_makedirs(stylepath)
    except OSError as e:
        if not (e.errno == errno_EEXIST and os_path_isdir(stylepath)):
            raise
    # Create CSS path
    stylesheet = os_path_join(stylepath, 'cdoc.css')
    # If using the user created custom CSS
    if external_css:
        copyfile(external_css, stylesheet)
    # If using the default CSS
    else:
        with open(stylesheet, 'w', encoding='utf-8') as file:
            file.write(STYLE)
            print('CDOC: {!r} processed'.format(stylesheet))
Ejemplo n.º 34
0
    def GET(self):
        URIs_especiales = {
            '_raices': 'self.indexar_json()',
            '_configuracion': 'self.indexar_configuracion()'
        }

        # 0 Si el valor es menor que 0
        acciones_parametros_especiales = {
            '_limite':
            ' datos_almacenados[ 0: 0 if int(valor_parametro_especial) < 0 else int(valor_parametro_especial) ] ',
            '_desde':
            ' datos_almacenados[ 0 if int(valor_parametro_especial) - 1 < 0 else int(valor_parametro_especial) - 1 : ]',
            '_total': ' {"total objetos":len(datos_almacenados)}'
        }

        trozos_URI, parametros, parametros_especiales = self.trocear_URI(
            parametros=True)

        if len(trozos_URI) == 0:

            if self.CONFIGURACION['SERVIDOR_ESTATICO']:

                try:

                    with open(
                            self.CONFIGURACION['PAGINA_ESTATICA_DIRECTORIO'] +
                            '/' +
                            self.CONFIGURACION['PAGINA_ESTATICA_ARCHIVO'],
                            'r') as PAGINA_ESTATICA:
                        self.devolver_estado(
                            200,
                            PAGINA_ESTATICA.read(),
                            nombre_archivo=self.
                            CONFIGURACION['PAGINA_ESTATICA_ARCHIVO'])

                except Exception as e:
                    self.indexar_json()

            else:
                self.indexar_json()

        elif trozos_URI[0] in URIs_especiales.keys():
            if not self.CONFIGURACION['URI_ESPECIALES']:
                self.devolver_estado(403)
                return

            eval(URIs_especiales[trozos_URI[0]])

        elif trozos_URI[0] == self.CONFIGURACION['PAGINA_ESTATICA_DIRECTORIO']:

            directorio = self.CONFIGURACION['PAGINA_ESTATICA_DIRECTORIO']
            for x in range(1, len(trozos_URI)):
                directorio += "/" + trozos_URI[x]

            if os_path_isdir(directorio):
                if self.CONFIGURACION['INDEXAR_DIRECTORIOS']:
                    codigo_estado, contenido, nombre_archivo = almacenamiento.leer_directorio(
                        directorio, trozos_URI,
                        self.CONFIGURACION['PAGINA_ESTATICA_ARCHIVO'],
                        self.CONFIGURACION[
                            'BUSCAR_PAGINA_ESTATICA_AL_INDEXAR_DIRECTORIO'])
                else:
                    codigo_estado, contenido, nombre_archivo = 403, False, False
                self.devolver_estado(codigo_estado, contenido, nombre_archivo)

            elif os_path_isfile(directorio):
                codigo_estado, contenido, nombre_archivo = almacenamiento.leer_archivo(
                    directorio, trozos_URI)
                self.devolver_estado(codigo_estado, contenido, nombre_archivo)

            else:
                self.devolver_estado(404)

        else:
            try:
                datos_almacenados = almacenamiento.leer_json(
                    self.CONFIGURACION, trozos_URI)

                # Si existen parametros, por cada parametro y por cada dato recuperado se comprueba, solo funciona con objetos
                if len(parametros) > 0:
                    if not isinstance(datos_almacenados, list):
                        self.devolver_estado(400)
                        return True

                    for parametro in parametros:
                        indice = 0

                        while indice < len(datos_almacenados):

                            if not isinstance(datos_almacenados[indice], dict):
                                self.devolver_estado(400)
                                return True

                            if not str(datos_almacenados[indice][
                                    parametro.split("=")[0]]) == str(
                                        parametro.split("=")[1]):
                                datos_almacenados.remove(
                                    datos_almacenados[indice])

                            else:
                                indice += 1

                # Si existen parametros especiales y estan permitidos, se recorren y ejecutan
                if len(parametros_especiales) > 0:
                    if not self.CONFIGURACION['PARAMETROS_ESPECIALES']:
                        self.devolver_estado(
                            403, 'PARAMETROS_ESPECIALES_DESACTIVADOS')
                        return True

                    if not isinstance(datos_almacenados, list):
                        self.devolver_estado(400)
                        return True

                    for parametro in parametros_especiales:
                        parametro_especial = parametro.split("=")[0]
                        try:
                            valor_parametro_especial = parametro.split("=")[1]
                        except:
                            valor_parametro_especial = None  # Para casos como ?_total

                        if parametro_especial in acciones_parametros_especiales.keys(
                        ):
                            datos_almacenados = eval(
                                acciones_parametros_especiales[
                                    parametro_especial])

                self.devolver_estado(200, datos_almacenados, es_json=True)

            except Exception as e:
                self.captura_error(str(e), cod_error=404, msg_error=str(e))
Ejemplo n.º 35
0
 def __init__(self, session, path_left = None):
     if path_left is None:
         if os_path_isdir(config.plugins.filecommander.path_left.value) and config.plugins.filecommander.savedir_left:
             path_left = config.plugins.filecommander.path_left.value
         else:
             path_left = config.plugins.filecommander.path_default.value
     if os_path_isdir(config.plugins.filecommander.path_right.value) and config.plugins.filecommander.savedir_right:
         path_right = config.plugins.filecommander.path_right.value
     else:
         path_right = config.plugins.filecommander.path_default.value
     if os_path_isdir(path_left) and path_left[-1] != '/':
         path_left += '/'
     if os_path_isdir(path_right) and path_right[-1] != '/':
         path_right += '/'
     self.session = session
     Screen.__init__(self, session)
     if config.plugins.filecommander.extension.value == 'myfilter':
         filter = '^.*\\.%s' % config.plugins.filecommander.my_extension.value
     else:
         filter = config.plugins.filecommander.extension.value
     self['list_left_head'] = Label(path_left)
     self['list_right_head'] = Label(path_right)
     self['list_left'] = FileList(path_left, matchingPattern=filter)
     self['list_right'] = FileList(path_right, matchingPattern=filter)
     self['key_red'] = Label(_('delete'))
     self['key_green'] = Label(_('move'))
     self['key_yellow'] = Label(_('copy'))
     self['key_blue'] = Label(_('rename'))
     self['actions'] = ActionMap(['ChannelSelectBaseActions',
      'WizardActions',
      'DirectionActions',
      'MenuActions',
      'NumberActions',
      'ColorActions',
      'TimerEditActions',
      'InfobarActions',
      'InfobarTeletextActions',
      'InfobarSubtitleSelectionActions'], {'ok': self.ok,
      'back': self.exit,
      'menu': self.goMenu,
      'nextMarker': self.listRight,
      'prevMarker': self.listLeft,
      'nextBouquet': self.listRight,
      'prevBouquet': self.listLeft,
      '1': self.gomakeDir,
      '2': self.gomakeSym,
      '3': self.gomakeSymlink,
      '4': self.call_change_mode,
      '5': self.goDefaultfolder,
      'startTeletext': self.file_viewer,
      'info': self.openTasklist,
      'up': self.goUp,
      'down': self.goDown,
      'left': self.goLeft,
      'right': self.goRight,
      'red': self.goRed,
      'green': self.goGreen,
      'yellow': self.goYellow,
      'blue': self.goBlue,
      '0': self.doRefresh,
      'showMovies': self.listSelect,
      'subtitleSelection': self.downloadSubtitles,
      'startTeletext': self.downloadSubtitles}, -1)
     if config.plugins.filecommander.path_left_selected:
         self.onLayoutFinish.append(self.listLeft)
     else:
         self.onLayoutFinish.append(self.listRight)
     self.onLayoutFinish.append(self.onLayout)
Ejemplo n.º 36
0
	def __init__(self, session, path_left=None):
		if path_left is None:
			if os_path_isdir(config.plugins.filecommander.path_left.value) and config.plugins.filecommander.savedir_left:
				path_left = config.plugins.filecommander.path_left.value
			else:
				path_left = config.plugins.filecommander.path_default.value

		if os_path_isdir(config.plugins.filecommander.path_right.value) and config.plugins.filecommander.savedir_right:
			path_right = config.plugins.filecommander.path_right.value
		else:
			path_right = config.plugins.filecommander.path_default.value

		if os_path_isdir(path_left) and path_left[-1] != "/":
			path_left += "/"

		if os_path_isdir(path_right) and path_right[-1] != "/":
			path_right += "/"

		self.session = session
		Screen.__init__(self, session)

		# set filter
		if config.plugins.filecommander.extension.value == "myfilter":
			filter = "^.*\.%s" % config.plugins.filecommander.my_extension.value
		else:
			filter = config.plugins.filecommander.extension.value

		# set current folder
		self["list_left_head"] = Label(path_left)
		self["list_right_head"] = Label(path_right)
		self["list_left"] = FileList(path_left, matchingPattern=filter)
		self["list_right"] = FileList(path_right, matchingPattern=filter)

		self["key_red"] = Label(_("Delete"))
		self["key_green"] = Label(_("Move"))
		self["key_yellow"] = Label(_("Copy"))
		self["key_blue"] = Label(_("Rename"))
		self["VKeyIcon"] = Pixmap()
		self["VKeyIcon"].hide()

		self["actions"] = ActionMap(["ChannelSelectBaseActions", "WizardActions", "DirectionActions", "MenuActions", "NumberActions", "ColorActions", "TimerEditActions", "InfobarActions", "InfobarTeletextActions", "InfobarSubtitleSelectionActions"], {
			"ok": self.ok,
			"back": self.exit,
			"menu": self.goMenu,
			"nextMarker": self.listRight,
			"prevMarker": self.listLeft,
			"nextBouquet": self.listRight,
			"prevBouquet": self.listLeft,
			"1": self.gomakeDir,
			"2": self.gomakeSym,
			"3": self.gomakeSymlink,
			"4": self.call_change_mode,
			"5": self.goDefaultfolder,
			# "8": self.test,
			"startTeletext": self.file_viewer,
			"info": self.openTasklist,
			"up": self.goUp,
			"down": self.goDown,
			"left": self.goLeft,
			"right": self.goRight,
			"red": self.goRed,
			"green": self.goGreen,
			"yellow": self.goYellow,
			"blue": self.goBlue,
			"0": self.doRefresh,
			"showMovies": self.listSelect,
			"subtitleSelection": self.downloadSubtitles,
		}, -1)

		if config.plugins.filecommander.path_left_selected:
			self.onLayoutFinish.append(self.listLeft)
		else:
			self.onLayoutFinish.append(self.listRight)

		self.onLayoutFinish.append(self.onLayout)
Ejemplo n.º 37
0
def leer_directorio(directorio, trozos_URI, archivo_pagina_estatica,
                    buscar_archivo_pag_estatica):
    archivos_en_dire = os_listdir(directorio)
    if buscar_archivo_pag_estatica and archivo_pagina_estatica in archivos_en_dire:
        codigo, contenido, nom_archivo = leer_archivo(
            directorio + "/" + archivo_pagina_estatica, trozos_URI)
        return codigo, contenido, nom_archivo

    directorio_padre = "/"

    for dire_en_rama in range(len(trozos_URI) - 1):
        directorio_padre += trozos_URI[dire_en_rama] + "/"

    html = '<!DOCTYPE html>\
            <html lang="en">\
            <head>\
                <meta charset="UTF-8">\
                <meta name="viewport" content="width=device-width, initial-scale=1.0">\
                <meta http-equiv="X-UA-Compatible" content="ie=edge">\
                <title>' + directorio + '</title>\
                <style>\
                    table{\
                        width:100%;\
                        margin: 0 15px;\
                    }\
                    .directorio {\
                        border-left: 3px solid blue;\
                        padding-left: 5px;\
                    }\
                    .archivo {\
                        border-left: 3px solid green;\
                        padding-left: 5px;\
                    }\
                    .archivo_peso, .directorio_cantidad {\
                        text-align: right;\
                    }\
                </style>\
            </head>\
            <body>\
                <h1>' + directorio + '</h1>\
                <table>\
                    <tr>\
                        <td class="directorio">\
                            <a href="' + directorio_padre + '">' + directorio_padre + '</a>\
                        </td>\
                    </tr>'

    for cosa in archivos_en_dire:
        if os_path_isdir(directorio + "/" + cosa):
            cantidad_objetos = str(len(os_listdir(directorio + "/" + cosa)))
            html += '<tr>\
                        <td class="directorio">\
                            <a href="/' + directorio + "/" + cosa + '">' + cosa + '/</a>\
                        </td>\
                        <td class="directorio_cantidad">' + cantidad_objetos + '</td>\
                        <td>Objetos</td>\
                    </tr>'

        else:
            peso, escala_peso = calcular_tamaño(directorio + "/" + cosa)
            html += '<tr>\
                        <td class="archivo">\
                            <a href="/' + directorio + "/" + cosa + '">' + cosa + '</a>\
                        </td>\
                        <td class="archivo_peso">' + peso + '</td>\
                        <td>' + escala_peso + '</td>\
                    </tr>'

    html += '   </table>\
            </body>\
        </html>'

    return 200, html, "/" + directorio
Ejemplo n.º 38
0
def exist(path):
	if os_path_exists(path) and os_path_isdir(path) and os_access(path, os_W_OK):
		return True;
	#endif
	return False;
Ejemplo n.º 39
0
    def __init__(self, session, path_left=None):
        if path_left is None:
            if os_path_isdir(config.plugins.filecommander.path_left.value
                             ) and config.plugins.filecommander.savedir_left:
                path_left = config.plugins.filecommander.path_left.value
            else:
                path_left = config.plugins.filecommander.path_default.value

        if os_path_isdir(config.plugins.filecommander.path_right.value
                         ) and config.plugins.filecommander.savedir_right:
            path_right = config.plugins.filecommander.path_right.value
        else:
            path_right = config.plugins.filecommander.path_default.value

        if os_path_isdir(path_left) and path_left[-1] != "/":
            path_left += "/"

        if os_path_isdir(path_right) and path_right[-1] != "/":
            path_right += "/"

        self.session = session
        Screen.__init__(self, session)

        # set filter
        if config.plugins.filecommander.extension.value == "myfilter":
            filter = "^.*\.%s" % config.plugins.filecommander.my_extension.value
        else:
            filter = config.plugins.filecommander.extension.value

        # set current folder
        self["list_left_head"] = Label(path_left)
        self["list_right_head"] = Label(path_right)
        self["list_left"] = FileList(path_left, matchingPattern=filter)
        self["list_right"] = FileList(path_right, matchingPattern=filter)

        self["key_red"] = Label(_("Delete"))
        self["key_green"] = Label(_("Move"))
        self["key_yellow"] = Label(_("Copy"))
        self["key_blue"] = Label(_("Rename"))
        self["VKeyIcon"] = Pixmap()
        self["VKeyIcon"].hide()

        self["actions"] = ActionMap(
            [
                "ChannelSelectBaseActions", "WizardActions",
                "DirectionActions", "MenuActions", "NumberActions",
                "ColorActions", "TimerEditActions", "InfobarActions",
                "InfobarTeletextActions", "InfobarSubtitleSelectionActions"
            ],
            {
                "ok": self.ok,
                "back": self.exit,
                "menu": self.goMenu,
                "nextMarker": self.listRight,
                "prevMarker": self.listLeft,
                "nextBouquet": self.listRight,
                "prevBouquet": self.listLeft,
                "1": self.gomakeDir,
                "2": self.gomakeSym,
                "3": self.gomakeSymlink,
                "4": self.call_change_mode,
                "5": self.goDefaultfolder,
                # "8": self.test,
                "startTeletext": self.file_viewer,
                "info": self.openTasklist,
                "up": self.goUp,
                "down": self.goDown,
                "left": self.goLeft,
                "right": self.goRight,
                "red": self.goRed,
                "green": self.goGreen,
                "yellow": self.goYellow,
                "blue": self.goBlue,
                "0": self.doRefresh,
                "showMovies": self.listSelect,
                "subtitleSelection": self.downloadSubtitles,
            },
            -1)

        if config.plugins.filecommander.path_left_selected:
            self.onLayoutFinish.append(self.listLeft)
        else:
            self.onLayoutFinish.append(self.listRight)

        self.onLayoutFinish.append(self.onLayout)
Ejemplo n.º 40
0
	def __init__(self, session,path_left=None):
		if path_left is None:
			if os_path_isdir(config.plugins.filebrowservti.path_left.value) and config.plugins.filebrowservti.savedir_left:
				path_left = config.plugins.filebrowservti.path_left.value
			else:
				path_left = config.plugins.filebrowservti.path_default.value
			
		if os_path_isdir(config.plugins.filebrowservti.path_right.value) and config.plugins.filebrowservti.savedir_right:
			path_right = config.plugins.filebrowservti.path_right.value
		else:
			path_right = config.plugins.filebrowservti.path_default.value

		self.session = session
		Screen.__init__(self, session)
		
		# set filter
		if config.plugins.filebrowservti.extension.value == "myfilter":
			filter = "^.*\.%s" % config.plugins.filebrowservti.my_extension.value
		else:
			filter = config.plugins.filebrowservti.extension.value
			
		# set actual folder
		HelpableScreen.__init__(self)
		self["list_left_head"] = Label(path_left)
		self["list_left_head_name"] = Label()
		self["list_left_head_state"] = Label()
		self["list_right_head"] = Label(path_right)
		self["list_right_head_name"] = Label()
		self["list_right_head_state"] = Label()
		self["list_left"] = FileList(path_left, matchingPattern = filter)
		self["list_right"] = FileList(path_right, matchingPattern = filter)

		self["help"] = Label(_("Help:\nKey [0] Refresh screen.\nKey [1] New folder.\nKey [2] New symlink wit name.\nKey [3] New symlink with foldername.\nKey [4] User rights 644/755.\nKey [5] Change to default folder. \nKey [8] Toggle sort direction up, down. \nKey [9] Toggle Quick-Help. \nKey [R] Select multiple files. \nKey [OK] Play movie and music, show pictures, view/edit files, install/extract files, run scripts. \nKey [EPG] Shows tasklist. Check copy/move progress in extensions menu. \nKey [TXT] View/Edit selected file. \nKey [Help] Shows Help."))
		self["helpBack"] = Label()
		self["helpShadow"] = Label()
		self['help'].hide()
		self['helpBack'].hide()
		self['helpShadow'].hide()
		helpOn = 0
		self.helpOn = helpOn
		
		self["key_red"] = Label(_("Delete"))
		self["key_green"] = Label(_("Move"))
		self["key_yellow"] = Label(_("Copy"))
		self["key_blue"] = Label(_("Rename"))

		self["ChannelSelectBaseActions"] = HelpableActionMap(self,"ChannelSelectBaseActions",
			{
				"prevBouquet": (self.listLeft, _("Select left window")),
				"nextBouquet": (self.listRight, _("Select right window")),
				"prevMarker": self.listLeft,
				"nextMarker": self.listRight,
			}, -1)

		self["WizardActions"] = HelpableActionMap(self, "WizardActions", 
			{
				"ok": (self.ok, _("Play movie & music, show pictures, view/edit files, install/extract files, run scripts")),
				"back": (self.exit,_("Exit")),
				"up": (self.goUp, _("Selection up")),
				"down": (self.goDown, _("Selection down")),
				"left": (self.goLeft, _("Page up")),
				"right": (self.goRight, _("Page down")),
			}, -1)

		self["MenuActions"] = HelpableActionMap(self, "MenuActions", 
			{
				"menu": (self.goMenu, _("Settings")),
			}, -1)

		self["NumberActions"] = HelpableActionMap(self, "NumberActions", 
			{
				"0": (self.doRefresh, _("Refresh screen")),
				"1": (self.gomakeDir, _("New folder")),
				"2": (self.gomakeSym, _("New symlink with name")),
				"3": (self.gomakeSymlink, _("New symlink with foldername")),
				"4": (self.call_change_mode, _("User rights 644/755")),
				"5": (self.goDefaultfolder, _("Change to default folder")),
				"8": (self.sortMode, _("Toggle sort direction up, down")),
				"9": (self.QuickHelp, _("Toogle Quick-Help")),
			}, -1)

		self["ColorActions"] = HelpableActionMap(self, "ColorActions", 
			{
				"red": (self.goRed, _("Delete")),
				"green": (self.goGreen, _("Move")),
				"yellow": (self.goYellow, _("Copy")),
				"blue": (self.goBlue, _("Rename")),
			}, -1)

		self["TimerEditActions"] = HelpableActionMap(self, "TimerEditActions", 
			{
				"eventview": (self.openTasklist, _("Show tasklist. Check copy/move progress in extensions menu")),
			}, -1)

		self["InfobarTeletextActions"] = HelpableActionMap(self, "InfobarTeletextActions", 
			{
				"startTeletext": (self.file_viewer, _("View/Edit files")),
			}, -1)

		self["InfobarActions"] = HelpableActionMap(self, "InfobarActions", 
			{
				"showMovies": (self.listSelect,  _("Multiselection list")),
			}, -1)

		if config.plugins.filebrowservti.path_left_selected:
			self.onLayoutFinish.append(self.listLeft)
		else:
			self.onLayoutFinish.append(self.listRight)

		self.onLayoutFinish.append(self.onLayout)