Esempio n. 1
0
 def save_setting_to_file(content):
     makedirs(paths.jupyter_config_dir(), exist_ok=True)
     with fdopen(
             osopen(EnvironmentSettings.config_path,
                    O_RDWR | O_CREAT | O_TRUNC, 0o600), 'w+') as file:
         file.write(
             json.dumps(json.loads(content), indent=4, sort_keys=True))
Esempio n. 2
0
    def __init__(self):
        self.Devices = {}
        self.currentDevice = ""
        devices = listdir("/dev/input/")

        for device in devices:
            if isdir("/dev/input/%s" % device):
                continue
            try:
                _buffer = "\0" * 512
                self.fd = osopen("/dev/input/%s" % device, O_RDWR | O_NONBLOCK)
                self.name = ioctl(self.fd, self.EVIOCGNAME(256), _buffer)
                self.name = self.name[:self.name.find(b"\0")]
                self.name = ensure_str(self.name)
                if str(self.name).find("Keyboard") != -1:
                    self.name = 'keyboard'
                osclose(self.fd)
            except (IOError, OSError) as err:
                print(
                    "[InputDevice] Error: device='%s' getInputDevices <ERROR: ioctl(EVIOCGNAME): '%s'>"
                    % (device, str(err)))
                self.name = None

            if self.name:
                self.Devices[device] = {
                    'name': self.name,
                    'type': self.getInputDeviceType(self.name),
                    'enabled': False,
                    'configuredName': None
                }

                # load default remote control "delay" and "repeat" values for ETxxxx ("QuickFix Scrollspeed Menues" proposed by Xtrend Support)
                if getBoxType().startswith('et'):
                    self.setDeviceDefaults(device)
Esempio n. 3
0
	def setDeviceRepeat(self, device, value): # REP_PERIOD
		if self.getDeviceAttribute(device, "enabled"):
			# print("[InputDevices] setDeviceRepeat for device %s to %d ms" % (device, value))
			event = pack("LLHHi", 0, 0, 0x14, 0x01, int(value))
			fd = osopen("/dev/input/%s" % device, O_RDWR)
			oswrite(fd, event)
			osclose(fd)
Esempio n. 4
0
 def setDeviceDelay(self, device, value):  # REP_DELAY
     if self.getDeviceAttribute(device, 'enabled'):
         # print("[InputDevices] setDeviceDelay for device %s to %d ms" % (device, value))
         event = pack('LLHHi', 0, 0, 0x14, 0x00, int(value))
         fd = osopen("/dev/input/" + device, O_RDWR)
         oswrite(fd, event)
         osclose(fd)
	def __init__(self):
		self.devices = {}
		self.currentDevice = None
		for device in sorted(listdir("/dev/input/")):
			if isdir("/dev/input/%s" % device):
				continue
			try:
				buffer = b"\0" * 512
				self.fd = osopen("/dev/input/%s" % device, O_RDWR | O_NONBLOCK)
				self.name = ioctl(self.fd, self.EVIOCGNAME(256), buffer)
				osclose(self.fd)
				self.name = str(self.name[:self.name.find(b"\0")])
			except (IOError, OSError) as err:
				print("[InputDevice] Error: device='%s' getInputDevices <ERROR: ioctl(EVIOCGNAME): '%s'>" % (device, str(err)))
				self.name = None
			if self.name:
				devType = self.getInputDeviceType(self.name.lower())
				print("[InputDevice] Found device '%s' with name '%s' of type '%s'." % (device, self.name, "Unknown" if devType is None else devType.capitalize()))
				# What was this for?
				# if self.name == "aml_keypad":
				# 	print("[InputDevice] ALERT: Old code flag for 'aml_keypad'.")
				# 	self.name = "dreambox advanced remote control (native)"
				# if self.name in BLACKLIST:
				# 	print("[InputDevice] ALERT: Old code flag for device in blacklist.")
				# 	continue
				self.devices[device] = {
					"name": self.name,
					"type": devType,
					"enabled": False,
					"configuredName": None
				}
	def setDeviceDelay(self, device, value):  # REP_DELAY
		if self.getDeviceAttribute(device, "enabled"):
			# print("[InputDevice] setDeviceDelay DEBUG: Set device '%s' to %s ms." % (device, value))
			event = pack("LLHHi", 0, 0, 0x14, 0x00, int(value))
			fd = osopen("/dev/input/%s" % device, O_RDWR)
			oswrite(fd, event)
			osclose(fd)
Esempio n. 7
0
def hashcode_generator(path='TorFolderPath', password='******'):
    change_dir(path)
    with osopen(f"cmd /k tor --hash-password {password}") as p:
        cmd_info = p.read()
    for value in cmd_info.split():
        if all((value.startswith('16:'), len(value) == hashcode_len)):
            return value
    raise OSError(cmd_info)
Esempio n. 8
0
	def setDeviceDefaults(self, device):
		print("[InputDevice] setDeviceDefaults DEBUG: Device '%s'." % device)
		self.setDeviceAttribute(device, "configuredName", None)
		eventRepeat = pack("LLHHi", 0, 0, 0x14, 0x01, 100)
		eventDelay = pack("LLHHi", 0, 0, 0x14, 0x00, 700)
		fd = osopen("/dev/input/%s" % device, O_RDWR)
		oswrite(fd, eventRepeat)
		oswrite(fd, eventDelay)
		osclose(fd)
Esempio n. 9
0
 def save_setting_to_file(content):
     makedirs(paths.jupyter_config_dir(), exist_ok=True)
     with fdopen(osopen(EnvironmentSettings.config_path, O_RDWR | O_CREAT, 0o600), 'w+') as file:
         file_content = file.read()
         new_settings = json.loads(content)
         if file_content:
             saved_settings = json.loads(file_content)
             file.seek(0)
             file.truncate()
             for setting_name in new_settings['beakerx']:
                 saved_settings['beakerx'][setting_name] = new_settings['beakerx'][setting_name]
         else:
             saved_settings = new_settings
         file.write(json.dumps(saved_settings, indent=4, sort_keys=True))
Esempio n. 10
0
def reader_thread_func(filename, filter_, real_stdout):
    """
    Sit there, reading lines from the pipe `filename`, sending those for which
    `filter_()` returns False to `real_stdout`
    """
    with fdopen(osopen(filename, O_NONBLOCK | O_RDONLY)) as fd:
        while True:
            rlist, _, _ = select([fd], [], [])
            
            line = fd.readline()
            if not line:
                break
                
            elif not filter_(line):
                real_stdout.write(line)
Esempio n. 11
0
 def _save_credentials(credientials):
     cred_file = path.join(path.expanduser('~'), '.ava', '.credentials')
     email_enc = base64.b64encode(credientials['_email'].encode('utf-8'))
     token_enc = base64.b64encode(credientials['_token'].encode('utf-8'))
     umask_original = umask(0)
     try:
         fdesc = osopen(cred_file, O_WRONLY | O_CREAT | O_EXCL, stat.S_IRUSR | stat.S_IWUSR)
     finally:
         umask(umask_original)
     with fdopen(fdesc, 'wb') as f:
         f.write(email_enc + b'\n')
         f.write(token_enc)
     from os import stat as sstat
     fs = sstat(cred_file)
     print(fs.st_mode)
Esempio n. 12
0
def reader_thread_func(filename, filter_, real_stdout, filt_content):
    """
    Sit there, reading lines from the pipe `filename`, sending those for which
    `filter_()` returns False to `real_stdout`
    """
    with fdopen(osopen(filename, O_NONBLOCK | O_RDONLY)) as fd:
        while True:
            rlist, _, _ = select([fd], [], [])
            
            line = fd.readline()
            if not line:
                break
                
            elif filter_(line):
                filt_content.write(line)
            else:
                real_stdout.write(line)
Esempio n. 13
0
 def save_setting_to_file(content):
     makedirs(paths.jupyter_config_dir(), exist_ok=True)
     with fdopen(
             osopen(EnvironmentSettings.config_path, O_RDWR | O_CREAT,
                    0o600), 'w+') as file:
         file_content = file.read()
         new_settings = json.loads(content)
         if file_content:
             saved_settings = json.loads(file_content)
             file.seek(0)
             file.truncate()
             for setting_name in new_settings['beakerx']:
                 saved_settings['beakerx'][setting_name] = new_settings[
                     'beakerx'][setting_name]
         else:
             saved_settings = new_settings
         file.write(json.dumps(saved_settings, indent=4, sort_keys=True))
Esempio n. 14
0
    def __init__(self):
        self.devices = {}
        self.currentDevice = None
        for device in sorted(listdir("/dev/input/")):

            if isdir("/dev/input/%s" % device):
                continue
            try:
                _buffer = "\0" * 512
                self.fd = osopen("/dev/input/%s" % device, O_RDWR | O_NONBLOCK)
                self.name = ioctl(self.fd, self.EVIOCGNAME(256), _buffer)
                self.name = self.name[:self.name.find(b"\0")]
                self.name = ensure_str(self.name)
                if str(self.name).find("Keyboard") != -1:
                    self.name = 'keyboard'
                osclose(self.fd)
            except OSError as err:
                print(
                    "[InputDevice] Error: device='%s' getInputDevices <ERROR: ioctl(EVIOCGNAME): '%s'>"
                    % (device, str(err)))
                self.name = None

            if self.name:
                devType = self.getInputDeviceType(self.name.lower())
                print(
                    "[InputDevice] Found device '%s' with name '%s' of type '%s'."
                    % (device, self.name,
                       "Unknown" if devType is None else devType.capitalize()))
                # What was this for?
                # if self.name == "aml_keypad":
                # 	print("[InputDevice] ALERT: Old code flag for 'aml_keypad'.")
                # 	self.name = "dreambox advanced remote control (native)"
                # if self.name in BLACKLIST:
                # 	print("[InputDevice] ALERT: Old code flag for device in blacklist.")
                # 	continue
                self.devices[device] = {
                    "name": self.name,
                    "type": devType,
                    "enabled": False,
                    "configuredName": None
                }

                # load default remote control "delay" and "repeat" values for ETxxxx ("QuickFix Scrollspeed Menues" proposed by Xtrend Support)
                if getBoxType().startswith('et'):
                    self.setDeviceDefaults(device)
Esempio n. 15
0
 def bpgdecode(self,filename):
     msg=None
     cmd=self.bpgpath
     self.frames_index=0
     if len(self.frames): self.frames=[]
     if self.img:
         del self.img
         self.img=None
     if len(filename)>4 and filename[-4:].lower()=='.bpg':
         try:
             if not(isfile(filename) and access(filename,R_OK)):
                 msg=_('Unable to open')+'\"%s\"!'%filename
         except: return False
         if not(msg):
             err=0
             try:
                 imbuffer=''
                 if osflag:
                     fifo=osopen(self.fifo,O_RDONLY|O_NONBLOCK)
                     cmd+=' "'+realpath(filename)+'" '+self.fifo+\
                         ' >/dev/null 2>&1'
                     f=Popen(cmd,shell=True,stdin=None,stdout=None,\
                         stderr=None)
                     if fifo:
                         while True:
                             if f.poll()!=None: break;
                             try: data=osread(fifo,16777216)
                             except OSError as e:
                                 if e.errno==errno.EAGAIN or\
                                     e.errno==errno.EWOULDBLOCK: data=''
                                 else: raise
                             if len(data): imbuffer+=data
                         osclose(fifo)
                 else:
                     si=STARTUPINFO()
                     si.dwFlags|=1
                     si.wShowWindow=0
                     pname='\\\\.\\pipe\\'+basename(self.fifo)
                     tpipe=win32pipe.CreateNamedPipe(
                         pname,
                         win32pipe.PIPE_ACCESS_DUPLEX,
                         win32pipe.PIPE_TYPE_BYTE|win32pipe.PIPE_WAIT,
                         1,16777216,16777216,2000,None)
                     cmd+=' "'+realpath(filename)+'" '+pname
                     f=Popen(cmd,shell=False,stdin=None,stdout=None,\
                         stderr=None,bufsize=0,startupinfo=si)
                     win32pipe.ConnectNamedPipe(tpipe,None)
                     imbuffer=''
                     if version_info[0]<3: imbuffer=''
                     else: imbuffer=b''
                     if tpipe:
                         while True:
                             data=None
                             try: data=win32file.ReadFile(tpipe,16777216)
                             except: data=None
                             if not(data): break
                             if data[0]!=0: break
                             if len(data[1]): imbuffer+=data[1]
                     win32pipe.DisconnectNamedPipe(tpipe)
                     f.wait()
                 if len(imbuffer):
                     x,=unpack("i",imbuffer[0:4])
                     y,=unpack("i",imbuffer[4:8])
                     n,=unpack("i",imbuffer[8:12])
                     d,=unpack("i",imbuffer[12:16])
                     if n==0 and d==1:
                         try:
                             self.img=Image.frombytes('RGBA',(x,y),
                                 imbuffer[16:])
                         except: err=1
                     else:
                         self.scale=100.0
                         self.autoscale=self.scale
                         self.bitmap_text=str(x)+'x'+str(y)
                         self.imginfo='%.2f'%self.scale+'%@'+self.bitmap_text
                         ishift=8
                         dr=n*1000/d
                         while True:
                             try:
                                 n,=unpack("i",imbuffer[ishift:ishift+4])
                                 ishift+=4
                                 d,=unpack("i",imbuffer[ishift:ishift+4])
                                 ishift+=4
                             except: break
                             try:
                                 img=Image.frombytes('RGBA',(x,y),
                                     imbuffer[ishift:])
                             except: break
                             ishift+=(x*y*4)
                             self.frames.append([self.bitmapfrompil(img),n*1000/d])
                         else: err=1
                     del imbuffer
                 else: err=1
             except: err=1
             if err: msg=_('BPG decoding error!\n')
     else: msg=_('File')+' \"%s\" '%filename+_('is not a BPG-File!')
     if msg:
         wx.PostEvent(self,ShowEvent(SE_EVT_TYPE,-1,value=msg))
         if self.img:
             del self.img
             self.img=None
     else: return True
     return False
Esempio n. 16
0
def llopen(path, mode, flags, perms=0o777):
    fd = osopen(path, flags, perms)
    return fdopen(fd, mode)
Esempio n. 17
0
 def bpgdecode(self,filename):
     msg=None
     cmd=self.bpgpath+' -o '
     if self.img:
         del self.img
         self.img=None
     if len(filename)>4 and filename[-4:].lower()=='.bpg':
         try:
             if not(isfile(filename) and access(filename,R_OK)):
                 msg=_('Unable to open')+'\"%s\"!'%filename
         except: return False
         if not(msg):
             err=0
             try:
                 imbuffer=''
                 if osflag:
                     fifo=osopen(self.fifo,O_RDONLY|O_NONBLOCK)
                     cmd+=self.fifo+' "'+realpath(filename)+'"'+\
                         ' >/dev/null 2>&1'
                     f=Popen(cmd,shell=True,stdin=None,stdout=None,\
                         stderr=None)
                     if fifo:
                         while True:
                             if f.poll()!=None: break;
                             try: data=osread(fifo,16777216)
                             except OSError as e:
                                 if e.errno==errno.EAGAIN or\
                                     e.errno==errno.EWOULDBLOCK: data=''
                                 else: raise
                             if len(data): imbuffer+=data
                         osclose(fifo)
                 else:
                     si=STARTUPINFO()
                     si.dwFlags|=1
                     si.wShowWindow=0
                     pname='\\\\.\\pipe\\'+basename(self.fifo)
                     tpipe=win32pipe.CreateNamedPipe(
                         pname,
                         win32pipe.PIPE_ACCESS_DUPLEX,
                         win32pipe.PIPE_TYPE_BYTE|win32pipe.PIPE_WAIT,
                         1,16777216,16777216,2000,None)
                     cmd+=pname+' "'+realpath(filename)+'"'
                     f=Popen(cmd,shell=False,stdin=None,stdout=None,\
                         stderr=None,bufsize=0,startupinfo=si)
                     win32pipe.ConnectNamedPipe(tpipe,None)
                     imbuffer=''
                     if tpipe:
                         while True:
                             data=None
                             try: data=win32file.ReadFile(tpipe,16777216)
                             except: data=None
                             if not(data): break
                             if data[0]!=0: break
                             if len(data[1]): imbuffer+=data[1]
                     win32pipe.DisconnectNamedPipe(tpipe)
                     f.wait()
                 if len(imbuffer):
                     if imbuffer[0]=='a': mode='RGBA'
                     else: mode='RGB'
                     x,=unpack("i",imbuffer[1:5])
                     y,=unpack("i",imbuffer[5:9])
                     try: self.img=Image.fromstring(mode,(x,y),imbuffer[9:])
                     except: err=1
                     del imbuffer
                 else: err=1
             except: err=1
             if err: msg=_('BPG decoding error!\n')
     else: msg=_('File')+' \"%s\" '%filename+_('is not a BPG-File!')
     if msg:
         print msg
         errmsgbox(msg)
         if self.img:
             del self.img
             self.img=None
     else: return True
     return False
Esempio n. 18
0
  if connector == 'socketpipe':
    connectorPair[0], connectorPair[1] = socketpair(AF_UNIX, SOCK_DGRAM)
  elif connector == 'pipe':
    connectorPair[0], connectorPair[1] = pipe()
  else:
    print 'Do not understand connector %s' % connector
    exit(1)
  node_index_out = processPair / 10
  node_index_inp = processPair % 10
  debug("out: %d, inp: %d, connector[0]: %d, connector[1]: %d\n" % (node_index_out, node_index_inp, connectorPair[0].fileno(), connectorPair[1].fileno()))
  setupProcess(node_index_out, 'output', connectorPair)
  setupProcess(node_index_inp, 'input', connectorPair)

# Open output file
if outFile:
  outfile_fd = osopen(outFile, O_WRONLY | O_CREAT)

# Activate interconnections and execute processes
for index, process in Process.processes.iteritems():
  debug('process %s, input channels: %d, output channels: %d\n' \
         % (process.command, len(process.inputConnectors), \
            len(process.outputConnectors)))
  pid = fork()
  if pid:
    debug("%s: inputConnectors: %d\n" % (process.command, len(process.inputConnectors)))
    if process.inputConnectors:
        environ["DGSH_IN"] = "1"
    else:
        environ["DGSH_IN"] = "0"
    for ic in process.inputConnectors:
      fd = process.selectInputFileDescriptor()
Esempio n. 19
0
def extract(archivePath, destDir, rename = None):
	'''Extract the given archive to the given directory.
	If a rename function is given, it is called with the output path relative
	to the destination directory; the value returned by the rename function is
	used as the actual relative destination file path.
	This function sets file ownership and permissions like is done in newly
	created files and ignores the ownership and permissions from the archive,
	since we are not restoring a backup.
	'''
	absDestDir = abspath(destDir) + sep
	if not isdir(absDestDir):
		raise ValueError(
			'Destination directory "%s" does not exist' % absDestDir
			)

	with TarFile.open(archivePath, errorlevel=2) as tar:
		for member in tar.getmembers():
			absMemberPath = abspath(joinpath(absDestDir, member.name))
			if member.isdir():
				absMemberPath += sep
			if not absMemberPath.startswith(absDestDir):
				raise ValueError(
					'Refusing to extract tar entry "%s" '
					'outside destination directory'
					% member.name
					)
			if rename:
				absMemberPath = absDestDir + rename(
					absMemberPath[len(absDestDir) : ]
					)

			if member.isfile():
				mode = S_IRWXU | S_IRWXG | S_IRWXO
				if not (member.mode & S_IXUSR):
					mode &= ~(S_IXUSR | S_IXGRP | S_IXOTH)
				fd = osopen(absMemberPath, O_CREAT | O_WRONLY | O_BINARY, mode)
				with fdopen(fd, 'wb') as out:
					inp = tar.extractfile(member)
					bytesLeft = member.size
					while bytesLeft > 0:
						buf = inp.read(bufSize)
						out.write(buf)
						bytesLeft -= len(buf)
			elif member.isdir():
				if not isdir(absMemberPath):
					mkdir(absMemberPath)
			elif member.issym():
				try:
					symlink(member.linkname, absMemberPath)
				except OSError as ex:
					print(
						'WARNING: Skipping symlink creation: %s -> %s: %s'
						% (absMemberPath, member.linkname, ex)
						)
			else:
				raise ValueError(
					'Cannot extract tar entry "%s": '
					'not a regular file, symlink or directory'
					% member.name
					)
			# Set file/directory modification time to match the archive.
			# For example autotools track dependencies between archived files
			# and will attempt to regenerate them if the time stamps indicate
			# one is older than the other.
			# Note: Apparently Python 2.5's utime() cannot set timestamps on
			#       directories in Windows.
			if member.isfile() or (
				member.isdir() and not hostOS.startswith('mingw')
				):
				utime(absMemberPath, (member.mtime, member.mtime))
Esempio n. 20
0
def extract(archivePath, destDir, rename=None):
    '''Extract the given archive to the given directory.
	If a rename function is given, it is called with the output path relative
	to the destination directory; the value returned by the rename function is
	used as the actual relative destination file path.
	This function sets file ownership and permissions like is done in newly
	created files and ignores the ownership and permissions from the archive,
	since we are not restoring a backup.
	'''
    absDestDir = abspath(destDir) + sep
    if not isdir(absDestDir):
        raise ValueError('Destination directory "%s" does not exist' %
                         absDestDir)

    tar = tarfile.open(archivePath)
    # Note: According to the Python 2.6 docs, errorlevel can be passed as a
    #       keyword argument to the open() call, but on Python 2.5 this does
    #       not work.
    tar.errorlevel = 2

    try:
        for member in tar.getmembers():
            absMemberPath = abspath(joinpath(absDestDir, member.name))
            if member.isdir():
                absMemberPath += sep
            if not absMemberPath.startswith(absDestDir):
                raise ValueError('Refusing to extract tar entry "%s" '
                                 'outside destination directory' % member.name)
            if rename:
                absMemberPath = absDestDir + rename(
                    absMemberPath[len(absDestDir):])

            if member.isfile():
                mode = S_IRWXU | S_IRWXG | S_IRWXO
                if not (member.mode & S_IXUSR):
                    mode &= ~(S_IXUSR | S_IXGRP | S_IXOTH)
                out = fdopen(
                    osopen(absMemberPath, O_CREAT | O_WRONLY | O_BINARY, mode),
                    'wb')
                try:
                    inp = tar.extractfile(member)
                    bytesLeft = member.size
                    while bytesLeft > 0:
                        buf = inp.read(bufSize)
                        out.write(buf)
                        bytesLeft -= len(buf)
                    buf = None
                finally:
                    out.close()
            elif member.isdir():
                if not isdir(absMemberPath):
                    mkdir(absMemberPath)
            else:
                raise ValueError('Cannot extract tar entry "%s": '
                                 'not a regular file or a directory' %
                                 member.name)
            # Set file/directory modification time to match the archive.
            # For example autotools track dependencies between archived files
            # and will attempt to regenerate them if the time stamps indicate
            # one is older than the other.
            # Note: Apparently Python 2.5's utime() cannot set timestamps on
            #       directories in Windows.
            if member.isfile() or hostOS != 'mingw32':
                utime(absMemberPath, (member.mtime, member.mtime))
    finally:
        tar.close()
Esempio n. 21
0
 def bpgdecode(self,filename):
     msg=None
     cmd='"'+self.bpgpath+'"'
     self.frames_index=0
     if len(self.frames): self.frames=[]
     if self.img:
         del self.img
         self.img=None
     if len(filename)>4 and filename[-4:].lower()=='.bpg':
         try:
             if not(isfile(filename) and access(filename,R_OK)):
                 msg=_('Unable to open')+'\"%s\"!'%filename
         except: return False
         if not(msg):
             err=0
             try:
                 if version_info[0]<3: imbuffer=''
                 else: imbuffer=b''
                 t,tmp=mkstemp(suffix='.rgb',prefix='')
                 close(t)
                 cmd+=' "'+realpath(filename)+'" '+tmp+' >/dev/null 2>&1'
                 f=Popen(cmd,shell=True,stdin=None,stdout=None,stderr=None)
                 f.wait()
                 fifo=osopen(tmp,O_RDONLY|O_NONBLOCK)
                 if fifo:
                     while True:
                         try: data=osread(fifo,16777216)
                         except OSError as e:
                             if e.errno==errno.EAGAIN or\
                                 e.errno==errno.EWOULDBLOCK:
                                     data=''
                                     continue
                             else: raise
                         if len(data): imbuffer+=data
                         else: break
                     osclose(fifo)
                 if exists(tmp):
                     try: remove(tmp)
                     except: pass
                 if len(imbuffer):
                     x,=unpack("i",imbuffer[0:4])
                     y,=unpack("i",imbuffer[4:8])
                     n,=unpack("i",imbuffer[8:12])
                     d,=unpack("i",imbuffer[12:16])
                     if n==0 and d==1:
                         try:
                             self.img=Image.frombytes('RGBA',(x,y),
                                 imbuffer[16:])
                         except: err=1
                     else:
                         self.scale=100.0
                         self.autoscale=self.scale
                         self.bitmap_text=str(x)+'x'+str(y)
                         self.imginfo='%.2f'%self.scale+'%@'+self.bitmap_text
                         ishift=8
                         dr=n*1000/d
                         while True:
                             try:
                                 n,=unpack("i",imbuffer[ishift:ishift+4])
                                 ishift+=4
                                 d,=unpack("i",imbuffer[ishift:ishift+4])
                                 ishift+=4
                             except: break
                             try:
                                 img=Image.frombytes('RGBA',(x,y),
                                     imbuffer[ishift:])
                             except: break
                             ishift+=(x*y*4)
                             self.frames.append([self.bitmapfrompil(img),n*1000/d])
                         else: err=1
                     del imbuffer
                 else: err=1
             except: err=1
             if err: msg=_('BPG decoding error!\n')
     else: msg=_('File')+' \"%s\" '%filename+_('is not a BPG-File!')
     if msg:
         wx.PostEvent(self,ShowEvent(SE_EVT_TYPE,-1,value=msg))
         if self.img:
             del self.img
             self.img=None
     else: return True
     return False
Esempio n. 22
0
def mpiexec():
    global totalProcs, nextRange, argvCopy, configLines, configIdx, appnum
    global validGlobalArgs, globalArgs, validLocalArgs, localArgSets

    validGlobalArgs = { '-l' : 0, '-usize' : 1, '-gdb' : 0, '-gdba' : 1, '-bnr' : 0, '-tv' : 0,
                        '-if' : 1, '-machinefile' : 1, '-kx' : 0, '-s' : 1,
                        '-gn' : 1, '-gnp' : 1, '-ghost' : 1, '-gpath' : 1, '-gwdir' : 1,
			'-gsoft' : 1, '-garch' : 1, '-gexec' : 1,
			'-genvall' : 0, '-genv' : 2, '-genvnone' : 0,
			'-genvlist' : 1 }
    validLocalArgs  = { '-n' : 1, '-np' : 1, '-host' : 1, '-path' : 1, '-wdir' : 1,
                        '-soft' : 1, '-arch' : 1,
			'-envall' : 0, '-env' : 2, '-envnone' : 0, '-envlist' : 1 }

    globalArgs   = {}
    localArgSets = {}
    localArgSets[0] = []

    totalProcs    = 0
    nextRange     = 0
    configLines   = []
    configIdx     = 0
    xmlForArgsets = []
    appnum        = 0

    if len(argv) < 2  or  argv[1] == '-h'  or  argv[1] == '-help'  or  argv[1] == '--help':
	usage()
    fullDirName = path.abspath(path.split(argv[0])[0])  # normalize for platform also
    mpdrun = path.join(fullDirName,'mpdrun.py')
    if not access(mpdrun,X_OK):
        print 'mpiexec: cannot execute mpdrun %s' % mpdrun
        exit(0);
    if argv[1] == '-file':
	if len(argv) != 3:
	    usage()
        xmlFilename = argv[2]
        globalArgs['-kx'] = 1
    else:
        if argv[1] == '-gdba':
            if len(argv) != 3:
                print '-gdba must be used only with a jobid'
                usage()
            execvpe(mpdrun,[mpdrun,'-ga',argv[2]],environ)
        elif argv[1] == '-configfile':
	    if len(argv) != 3:
	        usage()
            configFileFD = osopen(argv[2],O_RDONLY)
            configFile = fdopen(configFileFD,'r',0)
            configLines = configFile.readlines()
            configLines = [ x.strip() + ' : '  for x in configLines if x[0] != '#' ]
            tempargv = []
            for line in configLines:
                shOut = Popen3("/bin/sh -c 'for a in $*; do echo _$a; done' -- %s" % (line))
                for shline in shOut.fromchild:
                    tempargv.append(shline[1:].strip())    # 1: strips off the leading _
	    tempargv = [argv[0]] + tempargv[0:-1]   # strip off the last : I added
            collect_args(tempargv)
        else:
            collect_args(argv)

        machineFileInfo = read_machinefile(globalArgs['-machinefile'])
        xmlDOC = xml.dom.minidom.Document()
        xmlCPG = xmlDOC.createElement('create-process-group')
        xmlDOC.appendChild(xmlCPG)
        for k in localArgSets.keys():
            handle_argset(localArgSets[k],xmlDOC,xmlCPG,machineFileInfo)
        xmlCPG.setAttribute('totalprocs', str(totalProcs) )  # after handling argsets
        if globalArgs['-l']:
            xmlCPG.setAttribute('output', 'label')
        if globalArgs['-if']:
            xmlCPG.setAttribute('net_interface', globalArgs['-if'])
        if globalArgs['-s']:
            xmlCPG.setAttribute('stdin_goes_to_who', globalArgs['-s'])
        if globalArgs['-bnr']:
            xmlCPG.setAttribute('doing_bnr', '1')
        if globalArgs['-gdb']:
            xmlCPG.setAttribute('gdb', '1')
        if globalArgs['-tv']:
            xmlCPG.setAttribute('tv', '1')
        submitter = getpwuid(getuid())[0]
        xmlCPG.setAttribute('submitter', submitter)
        xmlFilename = '/tmp/%s_tempxml_%d' % (submitter,getpid())
        try:    unlink(xmlFilename)
	except: pass
        xmlFileFD = osopen(xmlFilename,O_CREAT|O_WRONLY|O_EXCL,0600)
        xmlFile = fdopen(xmlFileFD,'w',0)
        print >>xmlFile, xmlDOC.toprettyxml(indent='   ')
        # print xmlDOC.toprettyxml(indent='   ')    #### RMB: TEMP DEBUG
        xmlFile.close()
    if globalArgs['-kx']:
        execvpe(mpdrun,[mpdrun,'-f',xmlFilename],environ)
    else:
        execvpe(mpdrun,[mpdrun,'-delxmlfile',xmlFilename],environ)
    print 'mpiexec: exec failed for %s' % mpdrun
    exit(0);
Esempio n. 23
0
 def bpgdecode(self, filename):
     msg = None
     cmd = '"' + self.bpgpath + '"'
     self.frames_index = 0
     if len(self.frames): self.frames = []
     if self.img:
         del self.img
         self.img = None
     if len(filename) > 4 and filename[-4:].lower() == '.bpg':
         try:
             if not (isfile(filename) and access(filename, R_OK)):
                 msg = _('Unable to open') + '\"%s\"!' % filename
         except:
             return False
         if not (msg):
             err = 0
             try:
                 if version_info[0] < 3: imbuffer = ''
                 else: imbuffer = b''
                 t, tmp = mkstemp(suffix='.rgb', prefix='')
                 close(t)
                 cmd += ' "' + realpath(
                     filename) + '" ' + tmp + ' >/dev/null 2>&1'
                 f = Popen(cmd,
                           shell=True,
                           stdin=None,
                           stdout=None,
                           stderr=None)
                 f.wait()
                 fifo = osopen(tmp, O_RDONLY | O_NONBLOCK)
                 if fifo:
                     while True:
                         try:
                             data = osread(fifo, 16777216)
                         except OSError as e:
                             if e.errno==errno.EAGAIN or\
                                 e.errno==errno.EWOULDBLOCK:
                                 data = ''
                                 continue
                             else:
                                 raise
                         if len(data): imbuffer += data
                         else: break
                     osclose(fifo)
                 if exists(tmp):
                     try:
                         remove(tmp)
                     except:
                         pass
                 if len(imbuffer):
                     x, = unpack("i", imbuffer[0:4])
                     y, = unpack("i", imbuffer[4:8])
                     n, = unpack("i", imbuffer[8:12])
                     d, = unpack("i", imbuffer[12:16])
                     if n == 0 and d == 1:
                         try:
                             self.img = Image.frombytes(
                                 'RGBA', (x, y), imbuffer[16:])
                         except:
                             err = 1
                     else:
                         self.scale = 100.0
                         self.autoscale = self.scale
                         self.bitmap_text = str(x) + 'x' + str(y)
                         self.imginfo = '%.2f' % self.scale + '%@' + self.bitmap_text
                         ishift = 8
                         dr = n * 1000 / d
                         while True:
                             try:
                                 n, = unpack("i",
                                             imbuffer[ishift:ishift + 4])
                                 ishift += 4
                                 d, = unpack("i",
                                             imbuffer[ishift:ishift + 4])
                                 ishift += 4
                             except:
                                 break
                             try:
                                 img = Image.frombytes(
                                     'RGBA', (x, y), imbuffer[ishift:])
                             except:
                                 break
                             ishift += (x * y * 4)
                             self.frames.append(
                                 [self.bitmapfrompil(img), n * 1000 / d])
                         else:
                             err = 1
                     del imbuffer
                 else:
                     err = 1
             except:
                 err = 1
             if err: msg = _('BPG decoding error!\n')
     else: msg = _('File') + ' \"%s\" ' % filename + _('is not a BPG-File!')
     if msg:
         wx.PostEvent(self, ShowEvent(SE_EVT_TYPE, -1, value=msg))
         if self.img:
             del self.img
             self.img = None
     else:
         return True
     return False
Esempio n. 24
0
def extract(archivePath, destDir, rename = None):
	'''Extract the given archive to the given directory.
	If a rename function is given, it is called with the output path relative
	to the destination directory; the value returned by the rename function is
	used as the actual relative destination file path.
	This function sets file ownership and permissions like is done in newly
	created files and ignores the ownership and permissions from the archive,
	since we are not restoring a backup.
	'''
	absDestDir = abspath(destDir) + sep
	if not isdir(absDestDir):
		raise ValueError(
			'Destination directory "%s" does not exist' % absDestDir
			)

	tar = tarfile.open(archivePath)
	# Note: According to the Python 2.6 docs, errorlevel can be passed as a
	#       keyword argument to the open() call, but on Python 2.5 this does
	#       not work.
	tar.errorlevel = 2

	try:
		for member in tar.getmembers():
			absMemberPath = abspath(joinpath(absDestDir, member.name))
			if member.isdir():
				absMemberPath += sep
			if not absMemberPath.startswith(absDestDir):
				raise ValueError(
					'Refusing to extract tar entry "%s" '
					'outside destination directory'
					% member.name
					)
			if rename:
				absMemberPath = absDestDir + rename(
					absMemberPath[len(absDestDir) : ]
					)

			if member.isfile():
				mode = S_IRWXU | S_IRWXG | S_IRWXO
				if not (member.mode & S_IXUSR):
					mode &= ~(S_IXUSR | S_IXGRP | S_IXOTH)
				out = fdopen(
					osopen(absMemberPath, O_CREAT | O_WRONLY | O_BINARY, mode),
					'wb'
					)
				try:
					inp = tar.extractfile(member)
					bytesLeft = member.size
					while bytesLeft > 0:
						buf = inp.read(bufSize)
						out.write(buf)
						bytesLeft -= len(buf)
					buf = None
				finally:
					out.close()
			elif member.isdir():
				if not isdir(absMemberPath):
					mkdir(absMemberPath)
			elif member.issym():
				symlink(member.linkname, absMemberPath)
			else:
				raise ValueError(
					'Cannot extract tar entry "%s": '
					'not a regular file, symlink or directory'
					% member.name
					)
			# Set file/directory modification time to match the archive.
			# For example autotools track dependencies between archived files
			# and will attempt to regenerate them if the time stamps indicate
			# one is older than the other.
			# Note: Apparently Python 2.5's utime() cannot set timestamps on
			#       directories in Windows.
			if member.isfile() or not hostOS.startswith('mingw'):
				utime(absMemberPath, (member.mtime, member.mtime))
	finally:
		tar.close()