コード例 #1
0
ファイル: buildtools.py プロジェクト: mmrvka/xbmc
def process(template,
            filename,
            destname,
            copy_codefragment=0,
            rsrcname=None,
            others=[],
            raw=0,
            progress="default",
            destroot=""):

    if progress == "default":
        progress = EasyDialogs.ProgressBar(
            "Processing %s..." % os.path.split(filename)[1], 120)
        progress.label("Compiling...")
        progress.inc(0)
    # check for the script name being longer than 32 chars. This may trigger a bug
    # on OSX that can destroy your sourcefile.
    if '#' in os.path.split(filename)[1]:
        raise BuildError, "BuildApplet could destroy your sourcefile on OSX, please rename: %s" % filename
    # Read the source and compile it
    # (there's no point overwriting the destination if it has a syntax error)

    fp = open(filename, 'rU')
    text = fp.read()
    fp.close()
    try:
        code = compile(text + '\n', filename, "exec")
    except SyntaxError, arg:
        raise BuildError, "Syntax error in script %s: %s" % (filename, arg)
コード例 #2
0
ファイル: imgbrowse.py プロジェクト: Oize/pspstacklesspython
 def opendoc(self, *args):
     pathname = EasyDialogs.AskFileForOpen()  # Any file type
     if not pathname:
         return
     bar = EasyDialogs.ProgressBar('Reading and converting...')
     try:
         rdr = img.reader(imgformat.macrgb16, pathname)
     except img.error, arg:
         EasyDialogs.Message(repr(arg))
         return
コード例 #3
0
    def showProgress(self, minvalue, maxvalue, currentvalue):
        """
        Shows a progress bar according to the given values

        @param minvalue: minVlue of scale
        @param maxvalue: maxvlaue of scale
        @param currentvalue: the current value to show the progress
        """
        bar = EasyDialogs.ProgressBar(maxvalue)
        for i in range(currentvalue):
            bar.inc()
        del bar
コード例 #4
0
def process(template,
            filename,
            destname,
            copy_codefragment=0,
            rsrcname=None,
            others=[],
            raw=0,
            progress='default',
            destroot=''):
    if progress == 'default':
        if EasyDialogs is None:
            print 'Compiling %s' % (os.path.split(filename)[1], )
            process = None
        else:
            progress = EasyDialogs.ProgressBar(
                'Processing %s...' % os.path.split(filename)[1], 120)
            progress.label('Compiling...')
            progress.inc(0)
    if '#' in os.path.split(filename)[1]:
        raise BuildError, 'BuildApplet could destroy your sourcefile on OSX, please rename: %s' % filename
    fp = open(filename, 'rU')
    text = fp.read()
    fp.close()
    try:
        code = compile(text + '\n', filename, 'exec')
    except SyntaxError as arg:
        raise BuildError, 'Syntax error in script %s: %s' % (filename, arg)
    except EOFError:
        raise BuildError, 'End-of-file in script %s' % (filename, )

    if string.lower(filename[-3:]) == '.py':
        basename = filename[:-3]
        if MacOS.runtimemodel != 'macho' and not destname:
            destname = basename
    else:
        basename = filename
    if not destname:
        if MacOS.runtimemodel == 'macho':
            destname = basename + '.app'
        else:
            destname = basename + '.applet'
    if not rsrcname:
        rsrcname = basename + '.rsrc'
    try:
        os.remove(destname)
    except os.error:
        pass

    process_common(template, progress, code, rsrcname, destname, 0,
                   copy_codefragment, raw, others, filename, destroot)
    return
コード例 #5
0
ファイル: buildtools.py プロジェクト: xx312022850/pypy
def update(template, filename, output):
    if MacOS.runtimemodel == 'macho':
        raise BuildError, "No updating yet for MachO applets"
    if progress:
        progress = EasyDialogs.ProgressBar("Updating %s..."%os.path.split(filename)[1], 120)
    else:
        progress = None
    if not output:
        output = filename + ' (updated)'

    # Try removing the output file
    try:
        os.remove(output)
    except os.error:
        pass
    process_common(template, progress, None, filename, output, 1, 1)
コード例 #6
0
ファイル: dialogs_legacy.py プロジェクト: vowapp/inter
    def __init__(self, title='RoboFab...', ticks=0, label=''):
        """
		A progress bar.
		Availability: FontLab, Mac
		"""
        self._tickValue = 1

        if inFontLab:
            fl.BeginProgress(title, ticks)
        elif MAC and hasEasyDialogs:
            import EasyDialogs
            self._bar = EasyDialogs.ProgressBar(title,
                                                maxval=ticks,
                                                label=label)
        else:
            _raisePlatformError('Progress')
コード例 #7
0
def update(template, filename, output):
    if MacOS.runtimemodel == 'macho':
        raise BuildError, 'No updating yet for MachO applets'
    if progress:
        if EasyDialogs is None:
            print 'Updating %s' % (os.path.split(filename)[1], )
            progress = None
        else:
            progress = EasyDialogs.ProgressBar(
                'Updating %s...' % os.path.split(filename)[1], 120)
    else:
        progress = None
    if not output:
        output = filename + ' (updated)'
    try:
        os.remove(output)
    except os.error:
        pass

    process_common(template, progress, None, filename, output, 1, 1)
    return
コード例 #8
0
ファイル: RSA.py プロジェクト: yanwarsolah/RSAAPP
def enkripsi(direktori, filename, n, e, obj, kunci, user,file):
    '''
    untuk	: enkripsi file dengan kriptografi RSA
    param	: String direktori, String filename, int n, int e
    return	: Float waktu enkripsi, String fileenkripsi

    estimasi code : 13/Nov/2014
    ---------------------------
    menambahkan objek txt waktu
    untuk ditampilan nilai waktu akhir
    setelah proses enkripsi selesai.
    karena Thread tidak bisa menangkap return data dari suatu
    fungsi atau method.
    '''
    # estimasi code : 13/Nov/2014
    # menambahkan sedikit pengalihan kesalahan
    # jika suatu saat program terjadi error
    # karena sesuatu.
    # penambahan try dimaksudkan untuk
    # memberi tau user kesalahan yang terjadi
    # karena pada dasarnya Thread yang saya gunakan
    # berupa thread tanpa kita tahu letak kesalahannya dimana.
    try:
        # estimasi code : 13/Nov/2014
        # memulai waktu enkripsi
        # nilai waktu tersebut akan di simpan
        # ke variabel waktu_awal
        waktu_awal = time.clock()

        # estimasi code : 13/Nov/2014
        # mengeset tempat penyimpanan hasil file
        # yang selesai di enkripsi
        direktori = str(direktori)

        # estimasi code : 13/Nov/2014
        # menyimpan filename ke dalam
        # variabel filename yang sebelumnya
        # dilakukan pemformatan ke string
        # terlebih dahulu.
        filename = str(filename)

        # estimasi code : 13/Nov/2014
        # mengambil ekstensi file
        # dari filename. nilainya
        # yang di dapat adalah nama extensi file
        # tersebut. kita menggunakan fungsi ambil_nama_file
        # yang ada pada package Pendukung_Kripto.
        fileAekstensi = Pendukung_Kripto.ambil_nama_file(filename)

        # estimasi code : 13/Nov/2014
        # mengeset nama default name file
        # yang di jadikan nama file setelah proses
        # enkripsi selesai.
        nama_enkripsi = "enkripRSA-"


        # estimasi code : 13/Nov/2014
        # membuat tempat sekaligus nama file
        # yang digunakan untuk write binary file.
        # nilainya di simpan ke variabel namafile_enkripsi
        # sebagai contoh: [D:/enkripRSA-excel-perusahaan-dagang.xls]
        namafile_enkripsi = direktori + nama_enkripsi + fileAekstensi
        
        n = int(n)
        e = int(e)

        with open(filename, "rb") as rf:
            data_awal = rf.read()

        ## di ubah ke list
        data_awal = list(data_awal)

        ## ascii
        data_awal = [ord(i) for i in data_awal]

        ## padding add 5
        data_awal = [int(i + 1) for i in data_awal]

        # estimasi code : 13/Nov/2014
        # progress bar
        meter = EasyDialogs.ProgressBar('Enkripsi : ' + filename,
                                        maxval=len(data_awal),
                                        label='Starting',
                                        )

        ## proses enkripsi
        chiper = []
        for num,i in enumerate(data_awal):
            ch = int(gmpy2.digits(gmpy2.powmod(gmpy2.mpz(i),\
            gmpy2.mpz(e), gmpy2.mpz(n))))
            chiper.append(ch)
            msg = 'Data Chiper : %d' % ch
            meter.label(msg)
            meter.set(num)
            #time.sleep(0.1)
        '''
        chiper = [(int(gmpy2.digits(gmpy2.powmod(gmpy2.mpz(i),
        gmpy2.mpz(e), gmpy2.mpz(n))))) for i in data_awal]
        '''

        ## time akhir
        waktu_akhir = time.clock()  -  waktu_awal

        ## diubah ke string
        chiper = [str(i) for i in chiper]

        ## di join dengan pemisah spasi
        chiper = " ".join(chiper)

        ## simpan chiper
        with open(namafile_enkripsi,"wb") as enk:
            enk.write(chiper)

        ## return data
        ## index 0 : waktu akhir enkripsi
        ## index 1 : tempat penyimpanan hasil enkripsi
        obj.SetValue(str(waktu_akhir)[:6])
        notifikasi = "Berhasil Melakukan Enkripsi, silahkan cek : " + namafile_enkripsi
        notif = wx.MessageDialog(None, notifikasi, "Sukses", wx.OK)
        notif.ShowModal()
        
        # set Log aktivitas
        aktivitas = "ENKRIPSI"
        waktu = datetime.datetime.now().strftime("%y/%m/%d %H:%M")
        proses = str(waktu_akhir)[:5] + " Detik"
        list_datalog = [ aktivitas, user.replace("\n",""), waktu, 
                         proses, kunci.replace("\n",""), file.replace("\n","") ]
        file_datalog = 'virtualfile/data_log.log'
        hasil_datalog = DataLog.DataLog(file_datalog,list_datalog)
            
        if not hasil_datalog:
            pesan = "Pencatatan Log Gagal"
            notif = wx.MessageDialog(self,pesan, "Info",wx.ICON_WARNING)
            notif.ShowModal()
        # estimasi code : 13/Nov/2014
        # tidak mengembalikan nilai
        ##return [waktu_akhir, namafile_enkripsi]
    except:
        # estimasi code : 13/Nov/2014
        # menampilkan pesan kesalahan (pelemparan kesalahan)
        # jika terdapat kesalahan
        notifikasi = "Terjadi kesalahan saat melakukan enkripsi"
        notif = wx.MessageDialog(None, notifikasi, "Error", wx.ICON_ERROR)
        notif.ShowModal()
コード例 #9
0
        resize = True
    if os.path.isdir(arg):
        dirs.append(arg)
if len(dirs) == 0:
    EasyDialogs.Message("No directories specified")
    sys.exit(0)
# Now, another, simpler dialog, uses the system's folder-chooser dialog:
path = EasyDialogs.AskFolder("Choose destination directory")
if not path:
    sys.exit(0)
if not os.path.isdir(path):
    EasyDialogs.Message("Destination directory not found")
    sys.exit(0)
# and now a progress bar:
tot_numfiles = sum([len(os.listdir(d)) for d in dirs])
bar = EasyDialogs.ProgressBar("Processing", tot_numfiles)
for d in dirs:
    for item in os.listdir(d):
        bar.inc()
        try:
            objpict = Image.open(d + "/" + item)
            if resize: objpict.thumbnail((100, 100, 1))
            if rotationr: objpict = objpict.rotate(-90)
            if rotationl: objpict = objpict.rotate(90)
            objpict.save(path + "/" + item + "." + format, format)
        except:
            print item + " is not an image"
# and one last dialog...:
score = EasyDialogs.AskYesNoCancel("Do you like this program?")
if score == 1:
    EasyDialogs.Message("Wwowowowow, EasyDialog roolz, ;-)")
コード例 #10
0
def tile(filename, dialogbar, rootPath, exepath, zoomifyViewer, current,
         total):
    # open input file
    ds = Image.open(filename)
    width, height = ds.size
    zoomify = Zoomify(width, height)
    tilecount = zoomify.tileCountUpToTier[zoomify.numberOfTiers]
    divider = tilecount // 40

    if dialogbar:
        dialogProgressbar = EasyDialogs.ProgressBar(
            "Tiling file %s / %s" % (current, total), 100,
            "Processing the image:\n%s" % filename)
        dialogProgressbar.set(0, tilecount)
    else:
        prefix = "[" + str(current) + "/" + str(total) + "]"
        #suffix = filename
        suffix = ""
        consoleProgressbar = ConsoleProgressBar(prefix,
                                                suffix,
                                                1,
                                                tilecount,
                                                50,
                                                mode='fixed',
                                                char='#')

    if os.path.exists(os.path.join(exepath, "watermark.png")):
        dswatermark = reduce_opacity(
            Image.open(os.path.join(exepath, "watermark.png")), 0.1)
    else:
        dswatermark = None

    # create folder for the image
    folderName = os.path.basename(os.path.splitext(filename)[0])
    path = os.path.join(rootPath, folderName)
    if not os.path.exists(path):
        os.makedirs(path)

    # write ImageProperties.xml
    f = open(os.path.join(path, "ImageProperties.xml"), "w")
    f.write(
        """<IMAGE_PROPERTIES WIDTH="%d" HEIGHT="%d" NUMTILES="%d" NUMIMAGES="1" VERSION="1.8" TILESIZE="256" />"""
        % (width, height, tilecount))

    # Write the "index.html" with eather openLayers viewer of zoomify viewer
    viewerText = None
    if zoomifyViewer:
        viewerText = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
   <title>%s</title>   
      <meta http-equiv="content-type" content="text/html; charset=utf-8" />
      <meta http-equiv="content-language" content="en" />
        <style type="text/css">
           body {
	      margin:0;
	      padding:0;
           }    
	   .link {
	      position:absolute; 
	      top: 0px; 
	      left: 0px;
	      color: #fff;
	      z-index: -1; 
	   }           
        </style>    
</head>
<body>
  <center>
    <OBJECT CLASSID="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" CODEBASE="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" WIDTH="100%%" HEIGHT="100%%" ID="theMovie">
      <PARAM NAME="FlashVars" VALUE="zoomifyImagePath=.">
      <PARAM NAME="MENU" VALUE="FALSE">
      <PARAM NAME="SRC" VALUE="../ZoomifyViewer.swf">
	<EMBED FlashVars="zoomifyImagePath=." SRC="../ZoomifyViewer.swf" MENU="false" PLUGINSPAGE="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"  WIDTH="100%%" HEIGHT="100%%" NAME="theMovie"></EMBED>
    </OBJECT>
  </center>
  <a href="http://help.oldmapsonline.org/" class="link">Old Maps Online.org</a>
</body></html>""" % (folderName)

    else:
        viewerText = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>%s</title>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <meta http-equiv="content-language" content="en" />
        <style type="text/css">
           body {
	      margin:0;
	      padding:0;
           }    
	   .link {
	      position:absolute; 
	      top: 0px; 
	      left: 0px;
	      color: #fff;
	      z-index: -1; 
	   }           
        </style>    
    <script src="../OpenLayers.js"></script>    

<script type="text/javascript">
  function init(){	
    var width = %d;
    var height = %d;
    var zoomify = new OpenLayers.Layer.Zoomify("Zoomify", "./", new OpenLayers.Size(width, height));	       
    var options = {
	controls: [],
	maxExtent: new OpenLayers.Bounds(0, 0, width, height),
	maxResolution: Math.pow(2, zoomify.numberOfTiers-1),
	numZoomLevels: zoomify.numberOfTiers,
	units: 'pixels'
    };
    
    var map = new OpenLayers.Map("map", options);
    map.addLayer(zoomify);
    map.addControl(new OpenLayers.Control.PanZoomBar());
    map.addControl(new OpenLayers.Control.MouseDefaults());
    map.addControl(new OpenLayers.Control.KeyboardDefaults());

    map.setBaseLayer(zoomify);
    map.zoomToMaxExtent();
  };
</script>

</head>
  <body onload="init()">
    <div id="map"></div>
    <a href="http://help.oldmapsonline.org/" class="link">Old Maps Online.org</a>
  </body>
</html>""" % (folderName, width, height)

    f = open(os.path.join(path, "index.html"), 'w')
    f.write(viewerText)
    f.close()

    #import urllib2
    #urlf = urllib2.urlopen("ttp://www.oldmapsonline.org/publish/zoomify/ZoomifyViewer.swf","rb")
    #f = open(os.path.join(path,"ZoomifyViewer.swf"),'wb')
    #f.write( urlf.read() )
    #f.close()
    # generate base tiles

    tileno = 0

    for z in range(zoomify.numberOfTiers - 1, -1, -1):
        width, height = zoomify.tierImageSize[z]
        if ds.size != (width, height):
            ds = ds.resize((width, height), Image.ANTIALIAS)
        for y in range(0, height, 256):
            for x in range(0, width, 256):
                tileWidth, tileHeight = 256, 256
                if x + 256 > width:
                    tileWidth = width % 256
                if y + 256 > height:
                    tileHeight = height % 256
                #print x/256, y/256, x, y, tileWidth, tileHeight

                dstile = Image.new('RGB', (tileWidth, tileHeight))
                dstile.paste(ds, (-x, -y))
                write_jpeg(
                    os.path.join(path,
                                 zoomify.tilefilename(x / 256, y / 256, z)),
                    dstile, dswatermark)
                tileno += 1
                if dialogbar:
                    dialogProgressbar.inc()
                else:
                    consoleProgressbar.increment_amount()
                    consoleProgressbar.print_bar()

                #	print ".",
                # gdal.TermProgress_nocb(tileno/tilecount)

    if dialogbar:
        del dialogProgressbar
    else:
        del consoleProgressbar
    print
コード例 #11
0
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""
"""

__version__ = "$Id$"
#end_pymotw_header

import EasyDialogs
import time

meter = EasyDialogs.ProgressBar(maxval=0)
for i in xrange(1, 1001):
    msg = 'Bytes: %d' % i
    meter.label(msg)
    meter.set(i)
コード例 #12
0
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""
"""

__version__ = "$Id$"
#end_pymotw_header

import EasyDialogs
import time

meter = EasyDialogs.ProgressBar(
    'Making progress...',
    maxval=1000,
    label='Starting',
)
for i in xrange(1, 1001, 123):
    msg = 'Bytes: %d' % i
    meter.label(msg)
    meter.set(i)
    time.sleep(1)
コード例 #13
0
for num in dir:
    for item in os.listdir(num):
        val += 1

# Obviusly if path is not a dir, we want to exit
if os.path.isdir(path) :
    pass
else:
    # Third dialog, display feedback message, very simple and usefull
    EasyDialogs.Message("Directory not found")
    sys.exit(0)
    
# Fourth Dialog, this one is nice, a progress bar, 'val' is the max value, when we reach this, the
# bar is at 100% and disappear, with ProgressBar.inc(num=1), we can increment the number

bar = EasyDialogs.ProgressBar("Resizing", val) # Val is the total number of file
for num in dir:
    for item in os.listdir(num):
        bar.inc()
        try:
            objpict = Image.open(num + "/" + item)
            if resize:
                objpict.thumbnail((100, 100, 1))
            for i in range(rotationr):
                objpict = objpict.rotate(-90)
            for i in range(rotationl):
                objpict = objpict.rotate(90)
            objpict.save(path + "/" + item + "." + format, format)
        except:
            print item + " Not a image"
コード例 #14
0
ファイル: buildtools.py プロジェクト: mcyril/ravel-ftn
"""tools for BuildApplet and BuildApplication"""
コード例 #15
0
                                            cancel='Start',
                                            yes='',
                                            no='Cancel')
        if answer == 0:  #NO -> abort
            print "User aborted"
            break
        elif answer == 1:  #YES -> ??
            sys.exit(1)
        else:  #CANCEL -> start
            pass

    try:
        jtagobj = ProgressJTAG()
        if not options.fake_progress:
            jtagobj.showprogess = True
        jtagobj.bar = EasyDialogs.ProgressBar(
            'Programming %r' % options.filename[-50:], 100)
        showError = False
        try:
            connected = False
            jtagobj.data = binary
            jtagobj.bar.label('Connecting...')
            jtagobj.open(options.lpt)  #try to open port
            try:
                jtagobj.connect()  #try to connect to target
                connected = True
                if options.fake_progress: jtagobj.bar.set(10)

                jtagobj.bar.label('Erasing...')
                if options.erase_mode == 'mass' or options.erase_mode == 'all':
                    jtagobj.actionMassErase()
                elif options.erase_mode == 'main':
コード例 #16
0
ファイル: test_EasyDialogs.py プロジェクト: nocarryr/aja-gui
import sys
import time

import EasyDialogs

if __name__ == "__main__":
    progressBar = EasyDialogs.ProgressBar('Testing py2exe', 100,
                                          'Testing, testing, 1-2-3...')
    for i in range(100):
        time.sleep(0.001)
        progressBar.inc()

    print progressBar.curval
    sys.exit(progressBar.curval)
コード例 #17
0
    def save_cb(self, *args):
        if self.copy_but.active:
            outfile = GtkExtra.file_sel_box(title=_("Output File"))
            if outfile is None:
                return

        ds = self.viewarea1.active_layer().get_parent().get_dataset()
        bright_val = math.floor(self.bright_adjustment.value * 255 / 100)
        contrast_val = (100 + self.contrast_adjustment.value) / 100
        gamma_val = self.gamma_adjustment.value

        outarray = Numeric.zeros(
            (ds.RasterCount, ds.RasterYSize, ds.RasterXSize),
            typecode=Numeric.UnsignedInt8)

        try:
            size = ds.RasterYSize
            import EasyDialogs
            progress = EasyDialogs.ProgressBar(title='Working...', maxval=size)
        except:
            pass

        lut = []
        for i in range(256):
            value = i + math.floor(bright_val)
            if value < 0:
                value = 0
            elif value >= 255:
                value = 255
            if contrast_val != 1.0:
                value = value * contrast_val
            if value < 0:
                value = 0
            elif value >= 255:
                value = 255
            if gamma_val != 1:
                value = 255 * math.pow(
                    float(abs(value)) / 255, 1.0 / gamma_val)
            if value < 0:
                value = 0
            elif value >= 255:
                value = 255
            value = int(value)
            lut.append(value)

        lutarray = Numeric.array((lut), typecode=Numeric.UnsignedInt8)

        for m in range(ds.RasterCount):
            inband = ds.GetRasterBand(m + 1)
            for i in range(ds.RasterYSize):
                #inarray = inband.ReadAsArray()
                inarray = inband.ReadAsArray(0, i, inband.XSize, 1,
                                             inband.XSize,
                                             1)[0].astype(Numeric.UnsignedInt8)
                #outarray = Numeric.zeros(inarray.shape)

                try:
                    progress.label('Processing Band: ' + str(m + 1) +
                                   ', Line: ' + str(i))
                    progress.set(i)
                except:
                    pass

                outarray[m][i].flat[:] = Numeric.take(lutarray, inarray.flat)

        res_ds = gdalnumeric.OpenArray(outarray, ds)
        res_ds = gview.manager.add_dataset(res_ds)

        view = gview.app.sel_manager.get_active_view_window()
        if self.copy_but.active:
            driver = ds.GetDriver()
            driver.CreateCopy(outfile, res_ds)
            view.file_open_by_name(outfile)
            self.destroy()
        elif self.owrite_but.active:
            for layer in gview.app.sel_manager.get_active_view().list_layers():
                if gvutils.is_of_class(layer.__class__, 'GvRasterLayer') == 1:
                    if layer.get_parent().get_dataset().GetDescription(
                    ) == ds.GetDescription():
                        gview.app.sel_manager.get_active_view().remove_layer(
                            layer)

            fname = ds.GetDescription()
            driver = ds.GetDriver()
            driver.CreateCopy(fname, res_ds)
            view.file_open_by_name(fname)
            view.refresh_cb()
            self.destroy()

        del ds
        del res_ds
        del outarray
コード例 #18
0
ファイル: mw_dialogs.py プロジェクト: ystallonne/grins
 def __init__(self, title, cancelcallback=None, parent=None):
     import EasyDialogs
     self.cancelcallback = cancelcallback
     self.progressbar = EasyDialogs.ProgressBar(title)
     self.oldlabel = ""
     self.oldvalues = (0, 0)
コード例 #19
0
ファイル: imgbrowse.py プロジェクト: mcyril/ravel-ftn
"""imgbrowse - Display pictures using img"""
コード例 #20
0
ファイル: RSA.py プロジェクト: yanwarsolah/RSAAPP
def dekripsi(direktori, filename, n, d, obj, kunci, user,file):
    '''
    untuk	: dekripsi file dengan kriptografi RSA
    param	: String direktorim String filename, int n, int d
    return	: Float waktu dekripsi, String file dekripsi
    '''
    ## set time awal
    waktu_awal = time.clock()

    direktori = str(direktori)  ## tempat penyimpana hasil enkripsi
    ##  D:/excel-perusahaan-dagang.xls
    filename = str(filename)
    fileAekstensi = Pendukung_Kripto.ambil_nama_file(filename)
    nama_dekripsi = "dekripsiRSA-"

    ##  D:/dekripRSA-excel-perusahaan-dagang.xls
    namafile_dekripsi = direktori + nama_dekripsi + fileAekstensi



    with open(filename, "rb") as rf:
        data_awal = rf.read()

    ## pemisahan split spasi
    data_awal = data_awal.split(" ")

    ## mengubah ke integer
    data_awal = [int(i) for i in data_awal]

    # estimasi code : 13/Nov/2014
    # progress bar

    meter = EasyDialogs.ProgressBar('Dekripsi : ' + filename,
                                        maxval=len(data_awal),
                                        label='Starting',
                                        )

    ## dekripsi data
    data_dek = []
    num = 0
    for i in data_awal:
        dt = int(gmpy2.digits(gmpy2.powmod(gmpy2.mpz(i), \
        gmpy2.mpz(d), gmpy2.mpz(n))))
        data_dek.append(int(gmpy2.digits(gmpy2.powmod(gmpy2.mpz(i), \
        gmpy2.mpz(d), gmpy2.mpz(n)))))
        msg = 'Data Dekripsi : %d' % dt
        meter.label(msg)
        num += 1
        meter.set(num)
    '''data_dek = [(int(gmpy2.digits(gmpy2.powmod(gmpy2.mpz(i), \
    gmpy2.mpz(d), gmpy2.mpz(n))))) for i in data_awal]'''


    ## time akhir
    waktu_akhir = time.clock()  -  waktu_awal

    ## padd -1 ke data_dek
    data_dek = [int(i - 1) for i in data_dek]

    ## to char
    data_dek = [chr(i) for i in data_dek]

    ## join
    data_dek = "".join(data_dek)

    ## simpan data
    with open(namafile_dekripsi,"wb") as w:
        w.write(data_dek)

    ## return data
    notifikasi = "Berhasil Melakukan Dekripsi, silahkan cek : " + namafile_dekripsi
    notif = wx.MessageDialog(None, notifikasi, "Sukses", wx.OK)
    notif.ShowModal()
    obj.SetValue(str(waktu_akhir)[:6])
    ##return [str(waktu_akhir), namafile_dekripsi]
    
    # set Log aktivitas
    aktivitas = "DEKRIPSI"
    waktu = datetime.datetime.now().strftime("%y/%m/%d %H:%M")
    proses = str(waktu_akhir)[:5] + " Detik"
    list_datalog = [ aktivitas, user.replace("\n",""), waktu, 
                     proses, kunci.replace("\n",""), file.replace("\n","") ]
    file_datalog = 'virtualfile/data_log.log'
    hasil_datalog = DataLog.DataLog(file_datalog,list_datalog)
        
    if not hasil_datalog:
        pesan = "Pencatatan Log Gagal"
        notif = wx.MessageDialog(self,pesan, "Info",wx.ICON_WARNING)
        notif.ShowModal()
コード例 #21
0
def main():
    # - - - - - - - - - - - - - load binary or config - - - - - - - - - - - - - - -
    # if parameter is given use this filename, open a requester otherwise
    if len(sys.argv) < 2:
        options.filename = ask_for_binary()
        if options.filename is None:
            abort_on_user_request()
    else:
        options.filename = sys.argv[1]

    # - - - - - - - - - - - detect and handle config files  - - - - - - - - - - - -
    # interpret manifest files here
    if options.filename.endswith('.m43'):
        # this is a simple ini file with settings
        config_filename = options.filename
        options.filename = None
        config = ConfigParser.RawConfigParser()
        config.read(config_filename)
        interpret_config(config, root=os.path.dirname(config_filename))
        if options.readme:
            if options.viewer == 'browser':
                import webbrowser
                webbrowser.open(options.readme)
            else:
                EasyDialogs.Message(open(options.readme).read())
    elif options.filename.endswith('.z43'):
        # a zip file containing the manifest file and the binary and a readme
        config_filename = options.filename
        options.filename = None
        import zipfile
        archive = zipfile.ZipFile(config_filename)
        # in a loop, search for the manifest file
        for info in archive.infolist():
            if info.filename.endswith('.m43'):
                config_filename = options.filename
                config = ConfigParser.RawConfigParser()
                config.readfp(StringIO(archive.read(info.filename)))
                interpret_config(config, abspath=False)
        # get binary from zip file
        if options.filename:
            binary = msp430.memory.Memory()  # prepare downloaded data
            binary.loadFile(options.filename,
                            fileobj=BytesIO(archive.read(options.filename)))
        # get readme from zip file and display it
        if options.readme:
            readme_text = archive.read(options.readme)
            if options.viewer == 'browser':
                import webbrowser
                import tempfile
                import atexit
                tmp_name = tempfile.mktemp(options.readme)
                tmp = open(tmp_name, 'wb')
                tmp.write(readme_text)
                tmp.close()

                # ensure that the readme is deleted at the end
                def cleanup(filename=tmp_name):
                    os.remove(tmp_name)

                atexit.register(cleanup)
                webbrowser.open(tmp_name)
            else:
                EasyDialogs.Message(readme_text)

    # checks
    if binary is None:
        if options.filename is None:
            options.filename = ask_for_binary()
            if options.filename is None:
                abort_on_user_request()
        if not os.path.isabs(options.filename):
            options.filename = os.path.abspath(options.filename)
        if os.path.isfile(options.filename):
            binary = msp430.memory.load(
                options.filename)  # format=options.input_format)
        else:
            abort_on_error("File not found:\n%s" % (options.filename, ))

    if options.loop:
        # if in loop mode, ensure that there is a "ready to go" question in the loop
        options.ask_start = True

    # init
    jtag.init_backend(options.backend)
    if jtag.backend == jtag.CTYPES_TI:
        options.fake_progress = True

    # - - - - - - - - - - - - - - optional questions - - - - - - - - - - - - - - -
    if options.lpt == 'ask':
        #swap the buttons, so that cancel is the sparate button at left
        answer = EasyDialogs.AskYesNoCancel(
            "MSP430 downloader\n\nDownload '%s'?\n\n" % (options.filename, ),
            default=0,
            cancel="USB",
            yes="Parallel port",
            no="Cancel")
        if answer == 0:  # NO -> abort
            abort_on_user_request()
        elif answer == 1:  # YES -> parallel
            options.lpt = "1"
        else:  # CANCEL -> USB
            options.lpt = "TIUSB"

    # check for aliases for the interface
    if options.lpt == 'parallel':
        options.lpt = '1'

    # choose erase mode
    if options.erase_mode == 'ask':
        answer = EasyDialogs.AskYesNoCancel("Choose erase mode",
                                            default=0,
                                            yes="ALL",
                                            cancel="Main only",
                                            no="Cancel")
        if answer == 0:  # NO
            abort_on_user_request()
        elif answer == 1:  # YES
            options.erase_mode = 'mass'
        else:  # CANCEL
            options.erase_mode = 'main'

    # - - - - - - - - - - - - - - - - logging - - - - - - - - - - - - - - - - - -
    if options.debug:
        print('\n'.join(["%s: %r" % kv for kv in options.__dict__.items()]))

    # - - - - - - - - - - - - - main programming loop - - - - - - - - - - - - - -
    # capture console output
    sys.stdout = sys.stderr = StringIO()

    class ProgressJTAG(jtag.JTAG):
        def progess_update(self, count, total):
            self.bar.set(100 * count / total)

    while True:
        if options.ask_start:
            answer = EasyDialogs.AskYesNoCancel("""\
                Ready to program...

                1. Connect the programmer.
                2. Power on target
                3. Press 'Start'
                """,
                                                default=0,
                                                cancel='Start',
                                                yes='',
                                                no='Cancel')
            if answer == 0:  # NO -> abort
                print("User aborted")
                break
            elif answer == 1:  # YES -> ??
                sys.exit(1)
            else:  # CANCEL -> start
                pass

        try:
            jtagobj = ProgressJTAG()
            if not options.fake_progress:
                jtagobj.showprogess = True
            jtagobj.bar = EasyDialogs.ProgressBar(
                'Programming %r' % options.filename[-50:], 100)
            showError = False
            try:
                connected = False
                jtagobj.data = binary
                jtagobj.bar.label('Connecting...')
                jtagobj.open(options.lpt)  # try to open port
                try:
                    jtagobj.connect()  # try to connect to target
                    connected = True
                    if options.fake_progress:
                        jtagobj.bar.set(10)

                    jtagobj.bar.label('Erasing...')
                    if options.erase_mode == 'mass' or options.erase_mode == 'all':
                        jtagobj.actionMassErase()
                    elif options.erase_mode == 'main':
                        jtagobj.actionMainErase()
                    if options.fake_progress:
                        jtagobj.bar.set(20)

                    showError = True
                    jtagobj.bar.label('Programming...')
                    jtagobj.actionProgram()
                    if options.fake_progress:
                        jtagobj.bar.set(60)

                    jtagobj.bar.label('Verifying...')
                    jtagobj.actionVerify()
                    if options.fake_progress:
                        jtagobj.bar.set(100)
                finally:
                    if sys.exc_info()[:1]:  # if there is an exception pending
                        jtagobj.verbose = 0  # do not write any more messages
                    if connected:
                        jtagobj.bar.label('Reset...')
                        jtagobj.reset(1, 1)  # reset and release target
                    jtagobj.close()  # Release communication port
            finally:
                del jtagobj.bar  # close progress bar
        except IOError as e:
            if showError:
                EasyDialogs.Message(
                    'An error occoured: "%s"\n\nMessages:\n%s' %
                    (e, sys.stdout.getvalue()))
            else:
                EasyDialogs.Message("%s: Can't connect to target" % name)
        except (SystemExit, KeyboardInterrupt):
            raise
        except Exception as e:
            if options.debug:
                messages = sys.stdout.getvalue()
                sys.__stdout__.write(messages)
                traceback.print_exc(file=sys.__stdout__)
            EasyDialogs.Message('An error occoured: %s\nMessages:\n%s' %
                                (e, sys.stdout.getvalue()))
        else:
            messages = sys.stdout.getvalue()
            if options.debug:
                sys.__stdout__.write(messages)
            EasyDialogs.Message('Messages:\n%s\nSuccess!' % (messages, ))
        if not options.loop:
            break