示例#1
0
文件: ssl.py 项目: Stewori/jython
def get_default_verify_paths():
    """Return paths to default cafile and capath.
    """
    cafile, capath = None, None
    default_cert_dir_env = os.environ.get('SSL_CERT_DIR', None)
    default_cert_file_env = os.environ.get('SSL_CERT_FILE', None)

    java_cert_file = System.getProperty('javax.net.ssl.trustStore')

    if java_cert_file is not None and os.path.isfile(java_cert_file):
        cafile = java_cert_file
    else:
        if default_cert_dir_env is not None:
            capath = default_cert_dir_env if os.path.isdir(default_cert_dir_env) else None
        if default_cert_file_env is not None:
            cafile = default_cert_file_env if os.path.isfile(default_cert_file_env) else None

        if cafile is None:
            # http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html
            java_home = System.getProperty('java.home')
            for _path in ('lib/security/jssecacerts', 'lib/security/cacerts'):
                java_cert_file = os.path.join(java_home, _path)
                if os.path.isfile(java_cert_file):
                    cafile = java_cert_file
                    capath = os.path.dirname(cafile)

    return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None,
                              capath if capath and os.path.isdir(capath) else None,
                              'SSL_CERT_FILE', default_cert_file_env,
                              'SSL_CERT_DIR', default_cert_dir_env)
示例#2
0
def _mcvinit_classpath_hack():
    r"""Attempt location of mcidasv.jar, idv.jar, and visad.jar.
    
    This function will look for the JARs within the classpath, but will also
    try within the following (platform-dependent) paths:
        Windows: "C:\Program Files\McIDAS-V-System"
        OS X: "/Applications/McIDAS-V-System"
        Linux: ""
        
    Returns:
        A dictionary with "mcidasv", "idv", and "visad" keys.
    """
    classpath = System.getProperty('java.class.path')
    
    # supply platform-dependent paths to various JAR files
    # (in case they somehow are not present in the classpath)
    osname = System.getProperty('os.name')
    current_dir = os.path.normpath(os.getcwd())
    mcv_jar = os.path.join(current_dir, 'mcidasv.jar')
    idv_jar = os.path.join(current_dir, 'idv.jar')
    visad_jar = os.path.join(current_dir, 'visad.jar')
    
    # allow the actual classpath to override any default JAR paths
    for entry in classpath.split(System.getProperty('path.separator')):
        if entry.endswith('mcidasv.jar'):
            mcv_jar = entry
        elif entry.endswith('idv.jar'):
            idv_jar = entry
        elif entry.endswith('visad.jar'):
            visad_jar = entry
            
    return {'mcidasv': mcv_jar, 'idv': idv_jar, 'visad': visad_jar}
示例#3
0
文件: fix.py 项目: jeremi360/jythonfx
def getJavaFX():
    ver = jsys.getProperty("java.version")
    ver = ver.split(".")
    ver[-1] = float(ver[-1].replace("_", "."))
    ver[0] = float(str(ver[0]) + "." + str(ver[1]))
    ver.pop(1)

    print  ver

    if ver[0] <= 1.6:
        mess()

    elif ver[0] == 1.7:
        if ver[1] <= 0.11:
            mess()
            home = jsys.getProperty("java.home")

            try:
                jfxrt = os.path.join(home, "lib", "jfxrt.jar")
                sys.path.insert(0, jfxrt)

            except:
                part01 = "Nie można odnalesc biblioteki JavaFX(jfxrt.jar).\n"
                message = part01 + "Unable to find JavaFX lib (jfxrt.jar)."
                jop.showMessageDialog(None, message)
                sys.exit()

    else:
        pass
示例#4
0
def os_string():
	'''
	Return a string indicating the current OS formatted according to CMTK filename conventions
	Linux
	MacOSX-10.4
	MacOSX-10.5
	MacOSX-10.6
	CYGWIN
	'''
	from java.lang import System
	osname=System.getProperty("os.name")

	if osname.startswith('Windows'):
		return 'CYGWIN'
	elif osname.startswith('Linux'):
		return 'Linux'
	elif osname.startswith('Mac'):
		osversion=System.getProperty("os.version")
		match=re.match(r'10\.([0-9]+)(\.[0-9])*',osversion)
		if match==None:
			sys.exit('Unable to identify OS version: '+osversion)
		osmajor=match.group(1)
		iosmajor=int(osmajor)
		if iosmajor<4:
			myErr('Sorry CMTK requires MacOSX >=10.4')
		elif iosmajor>6:
			osmajor='6'
		return 'MacOSX-10.'+osmajor
	else:
		return None
def compile(files, javac=None, cpathopt="-classpath",
            cpath=None, options=None, sourcedir=None):
    cmd = []
    # Search order for a Java compiler:
    #   1. -C/--compiler command line option
    #   2. python.jythonc.compiler property (see registry)
    #   3. guess a path to javac
    if javac is None:
        javac = sys.registry.getProperty("python.jythonc.compiler")
    if javac is None:
        javac = findDefaultJavac()
    cmd.append(javac)
    # Extra options
    #   1. -J/--compileropts command line option (passed in options)
    #   2. python.jythonc.compileropts property
    if options is None:
        options = sys.registry.getProperty("python.jythonc.compileropts")
        if options:
            options = options.split()
    if options is None:
        options = []
    cmd.extend(options)
    # new:
    # Classpath:
    #   1. python.jythonc.classpath property
    #   +
    #   2. java.class.path property
    #   +
    #   3. sourcedir
    #   +
    #   4. sys.path
    if cpath is None:
        sep = java.io.File.pathSeparator
        cpath = []
        part = sys.registry.getProperty("python.jythonc.classpath")
        if part != None:
            cpath.extend(part.split(sep))
        part = getClasspath()
        if part != None:
            cpath.extend(part.split(sep))
        if sourcedir:
            cpath.append(sourcedir)
        cpath.extend(sys.path)
        cpath = sep.join(cpath)
        if System.getProperty("os.name")[:7] == 'Windows' and \
                        System.getProperty("java.version") < "1.2":
            cpath = '"%s"' % cpath
    cmd.extend([cpathopt, cpath])
    cmd.extend(files)
    print 'Compiling with args:', cmd

    try:
        proc = runtime.exec(cmd)
    except IOError, e:
        msg = '''%s

Consider using the -C/--compiler command line switch, or setting
the property python.jythonc.compiler in the registry.''' % e
        return 1, '', msg
示例#6
0
 def testOS(self):
    if Env.getOS() == OS.MAC:
       assert System.getProperty("os.name").startswith("Mac OS X")
    elif Env.getOS() == OS.WINDOWS:
       assert System.getProperty("os.name").startswith("Windows")
    elif Env.getOS() == OS.LINUX:
       assert System.getProperty("os.name").find("Linux") >= 0
    assert Env.getOSVersion() != None
示例#7
0
文件: config.py 项目: Tknika/openhab
def get_config_file_path():
    return System.getProperty(
        ConfigConstants.CONFIG_FILE_PROG_ARGUMENT,
        os.path.join(
            System.getProperty(
                ConfigConstants.CONFIG_DIR_PROG_ARGUMENT, 
                ConfigConstants.MAIN_CONFIG_FOLDER),
            ConfigConstants.MAIN_CONFIG_FILENAME))
示例#8
0
 def __init__(self, data):
     self.data = data
     self.userDir = System.getProperty("jes.plugins.user")
     self.systemDir = System.getProperty("jes.plugins.system")
     self.builtinDir = System.getProperty("jes.plugins.builtin")
     self.available = self.userDir is not None
     self.toRemove = []
     self.registerPluginsWithJESVersion()
def getScanningBrokerUri():
    
    uri = System.getProperty("org.eclipse.scanning.broker.uri")

    if (uri is None):
        uri = System.getProperty("GDA/gda.activemq.broker.uri")

    if (uri is None):
        uri = System.getProperty("gda.activemq.broker.uri")

    return uri;
示例#10
0
    def __init__(self):
        self.running = True
        menuBar = JMenuBar()
        
        menu = JMenu("File")
        menu.add(OpenAction(self))
        menu.add(CloseAction(self))
        menu.addSeparator()
        menu.add(QuitAction(self))
        self.addWindowListener(ProfelisWindowAdapter(self))
        menuBar.add(menu)

        self.setJMenuBar(menuBar)

        self.contentPane = JPanel()
        self.contentPane.layout = GridBagLayout()
        constraints = GridBagConstraints()

        self.blastLocation = JTextField(System.getProperty("user.home") + "/blast")
        self.databaseLocation = JTextField(System.getProperty("user.home") + "/blast/db")
        self.projects = JTabbedPane()
        
        constraints.gridx, constraints.gridy = 0, 0
        constraints.gridwidth, constraints.gridheight = 1, 1
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 0, 0
        self.contentPane.add(JLabel("Blast Location"), constraints)
        constraints.gridx, constraints.gridy = 1, 0
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.weightx, constraints.weighty = 1, 0
        self.contentPane.add(self.blastLocation, constraints)
        constraints.gridx, constraints.gridy = 2, 0
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 0, 0
        self.contentPane.add(JButton(BlastAction(self)), constraints)
        constraints.gridx, constraints.gridy = 3, 0
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 0, 0
        self.contentPane.add(JLabel("Database Location"), constraints)
        constraints.gridx, constraints.gridy = 4, 0
        constraints.fill = GridBagConstraints.HORIZONTAL
        constraints.weightx, constraints.weighty = 1, 0
        self.contentPane.add(self.databaseLocation, constraints)
        constraints.gridx, constraints.gridy = 5, 0
        constraints.fill = GridBagConstraints.NONE
        constraints.weightx, constraints.weighty = 0, 0
        self.contentPane.add(JButton(DatabaseAction(self)), constraints)
        constraints.gridx, constraints.gridy = 0, 1
        constraints.gridwidth, constraints.gridheight = 6, 1
        constraints.fill = GridBagConstraints.BOTH
        constraints.weightx, constraints.weighty = 1, 1
        self.contentPane.add(self.projects, constraints)
示例#11
0
文件: rtm.py 项目: hsnuhayato/tsml
def initCORBA():
	global rootnc, nshost, orb
	props = System.getProperties()
	
	args = string.split(System.getProperty("NS_OPT"))
	nshost = System.getProperty("NS_OPT").split(':')[2]
	if nshost == "localhost" or nshost == "127.0.0.1":
		nshost = socket.gethostname()
	print 'nshost =',nshost
	orb = ORB.init(args, props)

	nameserver = orb.resolve_initial_references("NameService");
	rootnc = NamingContextHelper.narrow(nameserver);
	return None
示例#12
0
文件: show.py 项目: hangal/unifi
    def __init__(self):
        sourcePath = System.getProperty("unifi.sp")
        uc_file = System.getProperty("unifi.read") 
        sourcePath = sourcePath.split(":")

        print "srcpath:", sourcePath
        print "uc_file:", uc_file

        self.panel = GuiPanel(sourcePath, uc_file)
        self.miner = TermMiner(Unit._current_unit_collection)
        self.panel.guessCallback = GythonCallback(self, self.miner)
        self.guessCallback = self.panel.guessCallback
        self.currentGraphRep = None

        #graphevents.clickNode = self.mouseClickNode
        graphevents.clickEdge = self.mouseClickEdge
        graphevents.mouseEnterEdge = self.mouseEnterEdge
        graphevents.mouseLeaveEdge = self.mouseLeaveEdge
        graphevents.mouseEnterNode = self.mouseEnterNode
        graphevents.mouseLeaveNode = self.mouseLeaveNode
        self.prevClicked = None

        EdgeEditorPopup.addItem("** UniFi Options **")

        disconnectEdgeItem = EdgeEditorPopup.addItem("Disconnect")
        disconnectEdgeItem.menuEvent = self.disconnectEdge

        vf.defaultNodeZooming(false)
        vf.defaultEdgeZooming(false)

        self.source = "None"

        self.miner.run()

        showAllClusters = System.getProperty("showall")
        if showAllClusters is None:
            from java.util import ArrayList
            arrayList = ArrayList()
            for r in self.miner.sortedReps:
                arrayList.add(r)

            self.panel.filterAndSortClusters(arrayList)

        self.panel.display_all()
        self.add(self.panel)
        
        # add the toolbar to the main UI window
        ui.dock(self)
    def getListOfAvailableFLVs(self):
        """Return list of .flv files that can be streamed."""
        scope = Red5.getConnectionLocal().getScope()
        serverRoot = System.getProperty('red5.root')
        filesMap = HashMap()
        try:
            print 'Getting the FLV files'
            flvs = scope.getResources("streams/*.flv")
            for file in flvs:
                fso = File(serverRoot + '/webapps/oflaDemo' + file.path)
                flvName = fso.getName()
                flvBytes = 0
                if hasattr(fso, 'length'):
                    flvBytes = fso.length()
                else:
                    print 'Length not found'
                
                lastMod = '0'
                if hasattr(fso, 'lastModified'):
                    lastMod = self.formatDate(Date(fso.lastModified()))
                else:
                    log.debug('Last modified not found')

                print 'FLV Name:', flvName
                print 'Last modified date:', lastMod
                print 'Size:', flvBytes
                print '-------'
                
                fileInfo = HashMap(3);
                fileInfo["name"] = flvName
                fileInfo["lastModified"] = lastMod
                fileInfo["size"] = flvBytes
                filesMap[flvName] = fileInfo
        except Exception, e:
            print 'Error in getListOfAvailableFLVs:', e
示例#14
0
def python_home():
	# Running 32 bit we prefer a Python in Wow6432Node if it exists:
	import platform, os
	if os.name == "java":
		# When running JyNI we cannot use platform.architecture(),
		# because it tries to load ctypes which crashes exactly due
		# to the 64 bit vs 32 bit issue we want to avoid here.
		# Note that platform.architecture() works well with plain
		# Jython, because if it cannot find ctypes at all it performs
		# some fallback.
		from java.lang import System
		arch = System.getProperty("sun.arch.data.model")+"bit"
	else:
		arch = platform.architecture()[0]
	if arch == "32bit":
		try:
			return QueryValue(HKEY_CURRENT_USER, key32)
		except WindowsError:
			pass
		try:
			return QueryValue(HKEY_LOCAL_MACHINE, key32)
		except WindowsError:
			pass
		if platform.uname()[4].endswith('64'):
			# Running 32 bit on a 64 bit platform we abort here
			return
	try:
		return QueryValue(HKEY_CURRENT_USER, key)
	except WindowsError:
		pass
	try:
		return QueryValue(HKEY_LOCAL_MACHINE, key)
	except WindowsError:
		pass
示例#15
0
def getfilesystemencoding():
    """
    Note: there's a copy of this method in _pydev_filesystem_encoding.py
    """
    try:
        ret = sys.getfilesystemencoding()
        if not ret:
            raise RuntimeError("Unable to get encoding.")
        return ret
    except:
        try:
            # Handle Jython
            from java.lang import System

            env = System.getProperty("os.name").lower()
            if env.find("win") != -1:
                return "ISO-8859-1"  # mbcs does not work on Jython, so, use a (hopefully) suitable replacement
            return "utf-8"
        except:
            pass

        # Only available from 2.3 onwards.
        if sys.platform == "win32":
            return "mbcs"
        return "utf-8"
示例#16
0
文件: Utils.py 项目: RunarFreyr/waz
def unversioned_sys_platform():
    """
	Get the unversioned platform name.
	Some Python platform names contain versions, that depend on
	the build environment, e.g. linux2, freebsd6, etc.
	This returns the name without the version number. Exceptions are
	os2 and win32, which are returned verbatim.
	@rtype: string
	@return: Unversioned platform name
	"""
    s = sys.platform
    if s == "java":
        # The real OS is hidden under the JVM.
        from java.lang import System

        s = System.getProperty("os.name")
        # see http://lopica.sourceforge.net/os.html for a list of possible values
        if s == "Mac OS X":
            return "darwin"
        elif s.startswith("Windows "):
            return "win32"
        elif s == "OS/2":
            return "os2"
        elif s == "HP-UX":
            return "hpux"
        elif s in ("SunOS", "Solaris"):
            return "sunos"
        else:
            s = s.lower()
    if s == "win32" or s.endswith("os2") and s != "sunos2":
        return s
    return re.split("\d+$", s)[0]
示例#17
0
    def __initKeyMap(self):
        os_name = System.getProperty("os.name")
        if os_name.startswith("Win"):
            exit_key = KeyEvent.VK_Z
        else:
            exit_key = KeyEvent.VK_D

        keyBindings = [
            (KeyEvent.VK_ENTER, 0, "jython.enter", self.enter),
            (KeyEvent.VK_DELETE, 0, "jython.delete", self.delete),
            (KeyEvent.VK_HOME, 0, "jython.home", self.home),
            (KeyEvent.VK_LEFT, InputEvent.META_DOWN_MASK, "jython.home", self.home),
            (KeyEvent.VK_UP, 0, "jython.up", self.history.historyUp),
            (KeyEvent.VK_DOWN, 0, "jython.down", self.history.historyDown),
            (KeyEvent.VK_PERIOD, 0, "jython.showPopup", self.showPopup),
            (KeyEvent.VK_ESCAPE, 0, "jython.hide", self.hide),

            ('(', 0, "jython.showTip", self.showTip),
            (')', 0, "jython.hideTip", self.hideTip),
            (exit_key, InputEvent.CTRL_MASK, "jython.exit", self.quit),
            (KeyEvent.VK_SPACE, InputEvent.CTRL_MASK, "jython.showPopup", self.showPopup),
            (KeyEvent.VK_SPACE, 0, "jython.space", self.spaceTyped),

            # Mac/Emacs keystrokes
            (KeyEvent.VK_A, InputEvent.CTRL_MASK, "jython.home", self.home),
            (KeyEvent.VK_E, InputEvent.CTRL_MASK, "jython.end", self.end),
            (KeyEvent.VK_K, InputEvent.CTRL_MASK, "jython.killToEndLine", self.killToEndLine),
            (KeyEvent.VK_Y, InputEvent.CTRL_MASK, "jython.paste", self.paste),
            ]

        keymap = JTextComponent.addKeymap("jython", self.text_pane.keymap)
        for (key, modifier, name, function) in keyBindings:
            keymap.addActionForKeyStroke(KeyStroke.getKeyStroke(key, modifier), ActionDelegator(name, function))
        self.text_pane.keymap = keymap
示例#18
0
文件: yay_core.py 项目: jacktasia/yay
	def start_config(self):
		os_name =  System.getProperty('os.name')
		self.os_sep = File.separator	
		self.has_dir = True
		self.ticks = 30 #default
		self.first_start = False
		self.has_started = False
		app_name = 'Yay'
		print "Operating System: %s." % os_name
		if os_name.find('Windows') != -1:
		    self.os = 'win'
		else:
		    self.os = 'other'

		self.prefs = Preferences.userNodeForPackage(YayPrefs().getClass())
		self.dir = self.prefs.get('image_folder','')
		self.ticks = self.prefs.getInt('speed',30)
		if self.dir == '':	
			self.set_dir()
		else:
			print self.dir
			
		print "Image folder: %s." % self.dir
		self._stopevent = threading.Event()
		self._sleepperiod = 1.0
		threading.Thread.__init__(self,name='GoGo')
		self.file_count = 0;
		self.countsec = 0
		self.is_paused = True
		self.loadup()		
		self.last_off()
		self.updateLabel()
示例#19
0
def unversioned_sys_platform():
	"""
	Return the unversioned platform name.
	Some Python platform names contain versions, that depend on
	the build environment, e.g. linux2, freebsd6, etc.
	This returns the name without the version number. Exceptions are
	os2 and win32, which are returned verbatim.

	:rtype: string
	:return: Unversioned platform name
	"""
	s = sys.platform
	if s == 'java':
		# The real OS is hidden under the JVM.
		from java.lang import System
		s = System.getProperty('os.name')
		# see http://lopica.sourceforge.net/os.html for a list of possible values
		if s == 'Mac OS X':
			return 'darwin'
		elif s.startswith('Windows '):
			return 'win32'
		elif s == 'OS/2':
			return 'os2'
		elif s == 'HP-UX':
			return 'hpux'
		elif s in ('SunOS', 'Solaris'):
			return 'sunos'
		else: s = s.lower()
	
	# powerpc == darwin for our purposes
	if s == 'powerpc':
		return 'darwin'
	if s == 'win32' or s.endswith('os2') and s != 'sunos2': return s
	return re.split('\d+$', s)[0]
示例#20
0
文件: Utils.py 项目: blaine/node
def unversioned_sys_platform():
	"""returns an unversioned name from sys.platform.
	sys.plaform is not very well defined and depends directly on the python source tree.
	The version appended to the names is unreliable as it's taken from the build environment at the time python was built,
	i.e., it's possible to get freebsd7 on a freebsd8 system.
	So we remove the version from the name, except for special cases where the os has a stupid name like os2 or win32.
	Some possible values of sys.platform are, amongst others:
		aix3 aix4 atheos beos5 darwin freebsd2 freebsd3 freebsd4 freebsd5 freebsd6 freebsd7
		generic irix5 irix6 linux2 mac netbsd1 next3 os2emx riscos sunos5 unixware7
	Investigating the python source tree may reveal more values.
	"""
	s = sys.platform
	if s == 'java':
		# The real OS is hidden under the JVM.
		from java.lang import System
		s = System.getProperty('os.name')
		# see http://lopica.sourceforge.net/os.html for a list of possible values
		if s == 'Mac OS X':
			return 'darwin'
		elif s.startswith('Windows '):
			return 'win32'
		elif s == 'OS/2':
			return 'os2'
		elif s == 'HP-UX':
			return 'hpux'
		elif s in ('SunOS', 'Solaris'):
			return 'sunos'
		else: s = s.lower()
	if s == 'win32' or s.endswith('os2') and s != 'sunos2': return s
	return re.split('\d+$', s)[0]
示例#21
0
def render(chart):
  from java.lang import System 
  if not System.getProperty("java.awt.headless"):
    w = Worker(chart)
    w.start()
    time.sleep(2)
    w.dispose()
示例#22
0
def initConfigToScriptRun():
  global startedNewServer
  loadProperties("config.py.properties")
  hideDisplay()
  hideDumpStack("true")
  # try connecting to a running server if it is already running ... 
  if connected=="false":
    try:
      URL="t3://"+adminServerListenAddress+":"+adminServerListenPort
      connect(userName, passWord, URL, userConfigFile="c2sConfigdevelopment", userKeyFile="c2sSecretdevelopment")
    except WLSTException:
      print 'No server is running at '+URL+', the script will start a new server'
  hideDumpStack("false")
  if connected=="false":
    print 'Starting a brand new server at '+URL+' with server name '+adminServerName
    print 'Please see the server log files for startup messages available at '+domainDir
    # If a config.xml exists in the domainDir, WLST will use that config.xml to bring up the server. 
    # If you would like WLST to overwrite this directory, you should specify overWriteRootDir='true' as shown below
    # startServer(adminServerName, domName, URL, userName, passWord,domainDir, overWriteRootDir='true')
    _timeOut = Integer(TimeOut)
    # If you want to specify additional JVM arguments, set them using startServerJvmArgs in the property file or below
    _startServerJvmArgs=startServerJvmArgs
    if (_startServerJvmArgs=="" and (System.getProperty("java.vendor").find("Sun")>=0 or System.getProperty("java.vendor").find("Oracle")>=0 or System.getProperty("java.vendor").find("Hewlett")>=0)):
      _startServerJvmArgs = " -XX:MaxPermSize=128m"
    if overWriteRootDir=='true':
      startServer(adminServerName, domName, URL, userName, passWord,domainDir, timeout=_timeOut.intValue(), overWriteRootDir='true', block='true', jvmArgs=_startServerJvmArgs)
    else:
      startServer(adminServerName, domName, URL, userName, passWord,domainDir, timeout=_timeOut.intValue(), block='true', jvmArgs=_startServerJvmArgs)
    startedNewServer=1
    print "Started Server. Trying to connect to the server ... "
    connect(userName, passWord, URL, userConfigFile="c2sConfigdevelopment", userKeyFile="c2sSecretdevelopment")
    if connected=='false':
      stopExecution('You need to be connected.')
def __getfilesystemencoding():
    '''
    Note: there's a copy of this method in interpreterInfo.py
    '''
    import sys
    try:
        ret = sys.getfilesystemencoding()
        if not ret:
            raise RuntimeError('Unable to get encoding.')
        return ret
    except:
        try:
            #Handle Jython
            from java.lang import System
            env = System.getProperty("os.name").lower()
            if env.find('win') != -1:
                return 'ISO-8859-1'  #mbcs does not work on Jython, so, use a (hopefully) suitable replacement
            return 'utf-8'
        except:
            pass
        
        #Only available from 2.3 onwards.
        if sys.platform == 'win32':
            return 'mbcs'
        return 'utf-8'
示例#24
0
def _getOsType( os=None ):
    """Select the OS behavior based on os argument, 'python.os' registry
    setting and 'os.name' Java property.
    os: explicitly select desired OS. os=None to autodetect, os='None' to
    disable 
    """
    
    os = str(os or sys.registry.getProperty( "python.os" ) or \
               System.getProperty( "os.name" ))

    _osTypeMap = (
        ( "nt", ( 'nt', 'Windows NT', 'Windows NT 4.0', 'WindowsNT',
                  'Windows 2000', 'Windows 2003', 'Windows XP', 'Windows CE',
                  'Windows Vista', 'Windows 7' )),
        ( "dos", ( 'dos', 'Windows 95', 'Windows 98', 'Windows ME' )),
        ( "mac", ( 'mac', 'MacOS', 'Darwin' )),
        ( "None", ( 'None', )),
        )
    foundType = None
    for osType, patterns in _osTypeMap:
        for pattern in patterns:
            if os.startswith( pattern ):
                foundType = osType
                break
        if foundType:
            break
    if not foundType:
        foundType = "posix" # default - posix seems to vary most widely

    return foundType
示例#25
0
def _java_getprop(name,default):

    from java.lang import System
    try:
        return System.getProperty(name)
    except:
        return default
示例#26
0
def get_java_location():
    from java.lang import System  # @UnresolvedImport
    jre_dir = System.getProperty("java.home")
    for f in [os.path.join(jre_dir, 'bin', 'java.exe'), os.path.join(jre_dir, 'bin', 'java')]:
        if os.path.exists(f):
            return f
    raise RuntimeError('Unable to find java executable')
示例#27
0
 def check(class_):
     is_windows = False
     try:
         from java.lang import System
         is_windows = "win" in System.getProperty('os.name').lower()
     except:
         is_windows = "win" in platform.system().lower()
     return is_windows
def _raise_import_failed(type_, name):
    error_msg, error_details = get_error_details()
    msg = ["Importing %s '%s' failed: %s" % (type_, name, error_msg),
           "PYTHONPATH: %s" % sys.path, error_details]
    if sys.platform.startswith('java'):
        from java.lang import System
        msg.insert(-1, 'CLASSPATH: %s' % System.getProperty('java.class.path'))
    raise DataError('\n'.join(msg))
示例#29
0
文件: rtm.py 项目: hsnuhayato/tsml
	def __init__(self, ref):
		self.ref = ref
		osname = System.getProperty("os.name")
		# assuming jython and rtcd are running on the same OS
		if osname == "Mac OS X":
			self.soext = ".dylib"
		else: 
			self.soext = ".so"
def check_java_version():
	java_version = System.getProperty('java.version')
	print java_version
	minor_version = int(java_version[2])
	if minor_version < 5 or minor_version > 8:
		main_logger.warn("UNSUPPORTED JAVA VERSION")
		main_logger.warn("Java version " + java_version + " is not supported by ConfigNOW. Commands may not function as intended")
		time.sleep(5)
示例#31
0
def _java_getprop(name, default):

    from java.lang import System
    try:
        value = System.getProperty(name)
        if value is None:
            return default
        return value
    except AttributeError:
        return default
示例#32
0
def init(confProps, configFolder):
    if caseData.getCaseObject('nsfw_model') is None:
        from java.lang import System
        file = System.getProperty('iped.root') + '/models/nsfw-keras-1.0.0.h5'
        model = load_model(file)
        #compile predict function to be used by multiple threads
        model._make_predict_function()
        caseData.putCaseObject('nsfw_model', model)
        logger.info('Loaded NSFW model ' + file)
    return
示例#33
0
def check_java_version():
    java_version = System.getProperty('java.version')
    print java_version
    minor_version = int(java_version[2])
    if minor_version < 5 or minor_version > 8:
        main_logger.warn("UNSUPPORTED JAVA VERSION")
        main_logger.warn(
            "Java version " + java_version +
            " is not supported. Commands may not function as intended")
        time.sleep(5)
示例#34
0
def get_java_location():
    from java.lang import System  # @UnresolvedImport
    jre_dir = System.getProperty("java.home")
    for f in [
            os.path.join(jre_dir, 'bin', 'java.exe'),
            os.path.join(jre_dir, 'bin', 'java')
    ]:
        if os.path.exists(f):
            return f
    raise RuntimeError('Unable to find java executable')
示例#35
0
文件: hrp.py 项目: 130s/openhrp3-1
def initCORBA():
    global rootnc, orb
    props = System.getProperties()

    args = string.split(System.getProperty("NS_OPT"))
    orb = ORB.init(args, props)

    nameserver = orb.resolve_initial_references("NameService")
    rootnc = NamingContextHelper.narrow(nameserver)
    return None
示例#36
0
文件: som.py 项目: dtopuzov/som
    def __init__(self, cmd):
        """Creates instance of application.

        Args:
            cmd (str): Name or path (with arguments if needs) to application.
        """
        self._cmd = cmd
        self._p = None
        self._is_win = "win" in system.getProperty('os.name').lower()
        self.is_visible = SI.SCREEN  # Hack to not break elements hierarchy.
示例#37
0
def create_tmp_dir(local_connection):
    property = "java.io.tmpdir"
    temp_dir = System.getProperty(property)
    path_separator = local_connection.getHostOperatingSystem(
    ).getFileSeparator()
    work_dir = "%s%swork%s" % (temp_dir, path_separator,
                               System.currentTimeMillis())
    work_dir_as_file = File(work_dir)
    work_dir_as_file.mkdir()
    return work_dir_as_file
示例#38
0
文件: program.py 项目: zackfuqua/jes
    def setupGUI(self, initialFilename):
        self.gui = JESUI(self)
        self.gui.windowSetting(None)

        self.setHelpArray()

        self.gui.changeSkin(JESConfig.getInstance().getStringProperty(
            JESConfig.CONFIG_SKIN))
        self.gui.show()

        if JESConfig.getInstance().getBooleanProperty(JESConfig.CONFIG_BLOCK):
            self.gui.editor.removeBox()
        else:
            self.gui.editor.addBox()

        if JESConfig.getInstance().getBooleanProperty(JESConfig.CONFIG_GUTTER):
            self.gui.turnOnGutter()
        else:
            self.gui.turnOffGutter()

        # Install the bridges.
        self.terpControl = InterpreterControl(self.gui, self.interpreter)
        self.replBuffer = REPLBuffer(self.interpreter, self.gui.commandWindow)

        # Open or create the file.
        if initialFilename is None:
            self.fileManager.newFile()
        else:
            self.fileManager.readFile(initialFilename)

        # Startup complete!
        startTimeNS = System.getProperty("jes.starttimens")
        if startTimeNS is not None:
            self.startupTimeSec = ((System.nanoTime() - long(startTimeNS)) /
                                   1000000000.0)

        # Show introduction window if settings could not be loaded (Either new
        # JES user or bad write permissions)
        config = JESConfig.getInstance()
        loadError = config.getLoadError()

        if loadError is not None:
            JOptionPane.showMessageDialog(
                self.gui,
                "Your JESConfig.properties file could not be opened!\n" +
                loadError.toString(), "JES Configuration",
                JOptionPane.ERROR_MESSAGE)
        elif config.wasMigrated():
            JOptionPane.showMessageDialog(
                self.gui, "Your settings were imported from JES 4.3.\n" +
                "JES doesn't use the JESConfig.txt file in " +
                "your home directory anymore, so you can delete it.",
                "JES Configuration", JOptionPane.INFORMATION_MESSAGE)
        elif not config.wasLoaded():
            introController.show()
示例#39
0
    def builderPhase1(self):
        Ganymede.debug("LDAPBuilderTask builderPhase1 running")

        self.dnsdomain = System.getProperty("ganymede.gash.dnsdomain")
        if not self.dnsdomain:
            raise RuntimeException(
                "LDAPBuilder not able to determine dns domain name")

        self.output_path = System.getProperty("ganymede.builder.output")
        if not self.output_path:
            raise RuntimeException(
                "LDAPBuilder not able to determine output directory")
        else:
            self.output_path = PathComplete.completePath(self.output_path)

        self.build_users_and_groups()
        self.build_netgroups()

        Ganymede.debug("LDAPBuilderTask builderPhase1 complete")
        return 1
示例#40
0
 def readInputStream(inputStream):
     reader = BufferedReader(InputStreamReader(inputStream))
     builder = StringBuilder()
     line = None
     while True:
         line = reader.readLine()
         if line is None:
             break
         builder.append(line)
         builder.append(System.getProperty("line.separator"))
     return builder.toString()
示例#41
0
    def __init__(self):

        PhantomJS.script_path = System.getProperty("java.io.tmpdir") + \
                                                    "/" + PhantomJS.script_name

        file = open(PhantomJS.script_path, "w")
        file.write(PhantomJS.script_data)
        file.close()

        cb.callbacks.printOutput("Script written to: " +
                                 PhantomJS.script_path)
示例#42
0
    def test_catch(self):
        from java.lang import Integer
        from java.lang import RuntimeException, IllegalArgumentException, NumberFormatException
        with self.assertRaises(NumberFormatException):  # Actual class
            Integer.parseInt("hello")
        with self.assertRaises(IllegalArgumentException):  # Parent class
            Integer.parseInt("hello")
        with self.assertRaises(RuntimeException):  # Grandparent class
            Integer.parseInt("hello")

        from java.lang import System
        from java.io import IOException
        try:
            System.getProperty("")
        except IOException:  # Unrelated class
            self.fail()
        except NumberFormatException:  # Child class
            self.fail()
        except IllegalArgumentException:  # Actual class
            pass
示例#43
0
    def run(self):
        # in the main thread, call:
        # j = JESHomeworkTurninThread()
        # then:
        # j.start()
        # Java will create a seperate thread.  That thread will
        # call this method's run method
        
        # do stuff here
        try:

            update = JESHomeworkTurninRunnable.JESHomeworkTurninRunnable('Submitting Assignment ....',self.gui)
            self.gui.swing.SwingUtilities.invokeLater( update )            
            self.homeworkSub.turnin()
            update = JESHomeworkTurninRunnable.JESHomeworkTurninRunnable('Done',self.gui)
            self.gui.swing.SwingUtilities.invokeLater( update )

            import user
            if System.getProperty('os.name').find('Mac') <> -1:
                DIRECTORY = user.home
            else:
                DIRECTORY = os.getcwd()

            MESSAGE="""The assignment has been submitted. A file named 
%s was created in the submission.
This file is an archive containing all of the files that 
you just submitted.  JES can delete the file for you, 
or JES can leave the file alone. If you choose to keep
the file, it will be located at %s. 
Would you like JES to delete %s for you? """%(self.zipName,DIRECTORY,self.zipName)

            options = ["Delete the File","Leave the File"]
            n = swing.JOptionPane.showOptionDialog(self.gui,
                     MESSAGE,
                     "Assignment Submission has completed",
                     swing.JOptionPane.YES_NO_OPTION,
                     swing.JOptionPane.QUESTION_MESSAGE,
                     None,     #don't use a custom Icon
                     options,  #the titles of buttons
                     options[0]) #default button title
            if n == 0:
                try:                
                    os.remove(self.zipName)
                except:
                    import sys
                    a,b,c=sys.exc_info()
                    print a,b,c
        except Exception, target:
            import sys
            a,b,c=sys.exc_info()
            print a,b,c
            update = JESHomeworkTurninRunnable.JESHomeworkTurninRunnable('Exception',self.gui)
            self.gui.swing.SwingUtilities.invokeLater( update )
示例#44
0
def download_selected_files():
    if len(__get_selected_files__()) == 0:
        return
    full_paths = []
    for f in __get_selected_files__():
        full_paths.append(get_data_path() + '/' + f)
    inst_id = System.getProperty(__instrument_id__)
    if inst_id is None:
        inst_id = 'DATA'
    z_name = inst_id.upper() + '_raw_' + str(int(time.time()))[2:] + '.zip'
    zip_files(full_paths, z_name, False)
    print 'data files have been zipped in ' + z_name
示例#45
0
def get_home_dir():
    homeDir = None

    # noinspection PyBroadException
    try:
        if Platform.isOSX():
            homeDir = System.getProperty(
                "UserHome")  # On a Mac in a Java VM, the homedir is hidden
        else:
            # homeDir = System.getProperty("user.home")
            homeDir = os.path.expanduser(
                "~")  # Should work on Unix and Windows
            if homeDir is None or homeDir == "":
                homeDir = System.getProperty("user.home")
            if homeDir is None or homeDir == "":
                homeDir = os.environ.get("HOMEPATH")
    except:
        pass

    if not homeDir: homeDir = "?"
    return homeDir
def detectProtocBinaryLocation():
    system = System.getProperty('os.name')

    if system == "Linux":
        os.chmod("./protoc-linux", 0755)
        return os.path.join(os.getcwd(), "protoc-linux")
    elif system.startswith("Mac "):
        os.chmod("./protoc-mac", 0755)
        return os.path.join(os.getcwd(), "protoc-mac")
    elif system.startswith("Windows "):
        return os.path.join(os.getcwd(), "protoc-windows.exe")
    else:
        raise RuntimeError("Unrecognized operating system: " + system)
示例#47
0
def getProperty(joptname, penvname):
    "Retrieve options from registry or value from environment"
    try:
        from java.lang import System
        #         print "System.getProperty(%r)=%r"%(joptname, System.getProperty(joptname))
        return System.getProperty(joptname)


#         from org.python.core import PySystemState
#         return PySystemState.registry.get(joptname)
    except ImportError:
        import os
        return os.getenv(penvname)
示例#48
0
	def _addfailure(self, message, frame):
		lines = []
		while frame != None:
			code = frame.f_code
			filename = code.co_filename
			print filename
			dir = System.getProperty('marathon.project.dir')
			if filename.find(dir) == 0 or filename.find('Untitled') == 0:
				lines.append(SourceLine(code.co_filename, code.co_name, frame.f_lineno))

			frame = frame.f_back

		self.playbackresult.addFailure(message, jarray.array(lines, SourceLine))
示例#49
0
def build_java_process_cmd(javaTestName):
    """
    Builds a list of args to provide to the jep_pipe method's call to
    subprocess.Popen.  This will take care of setting up the Java classpath
    and the -Djava.library.path variable necessary to run a Java main()
    from the command line.  This method should be used in conjunction with
    tests that get built into the jep.test jar and are Java mains().

    Args:
            javaTestName: a fully-qualified name of a Java class with a main()
                            method

    Returns:
            a list of values to be passed to jep_pipe (subprocess.Popen)
    """
    from java.lang import System
    cp = System.getProperty('java.class.path')

    lib_path = '-Djava.library.path='
    lib_path += System.getProperty("java.library.path")

    return ['java', '-ea', '-cp', cp, lib_path, javaTestName]
示例#50
0
    def _filepicker(self):
        """
        Run the filepicker and return if approved

        :return: boolean, true if approved
        """
        fileChooser = JFileChooser()
        fileChooser.setCurrentDirectory(File(System.getProperty("user.home")))
        result = fileChooser.showOpenDialog(self.this)
        isApproveOption = result == JFileChooser.APPROVE_OPTION
        if isApproveOption:
            selectedFile = fileChooser.getSelectedFile()
            self._omnibar.setText(selectedFile.getAbsolutePath())
        return isApproveOption
示例#51
0
def set_font():
    """
    Loads font from resources' ttf file.
    DejaVuSans doesn't work in Retina display screens properly, so check OS,
    if OSX then use Monaco instead.
    """
    if "mac" in System.getProperty("os.name").lower():
        font = Font("Monaco", Font.PLAIN, 14)
    else:
        path_to_ttf = 'resources/fonts/dejavu/ttf/DejaVuSans.ttf'
        loader = ClassLoader.getSystemClassLoader()
        stream = loader.getResourceAsStream(path_to_ttf)
        font = Font.createFont(Font.TRUETYPE_FONT, stream)
        font = font.deriveFont(Font.PLAIN, 14)
    return font
示例#52
0
    def __init__(self, frame, chart, lociNames, pv, ci, confLines, locusFst,
                 isDominant, fdr):
        JDialog(frame)
        self.chart = chart
        self.frame = frame
        self.confLines = confLines
        self.isDominant = isDominant
        self.fdr = fdr
        pane = self.getRootPane().getContentPane()

        pane.setLayout(BorderLayout())

        self.initTable(lociNames, pv, ci, locusFst)
        scrollPane = JScrollPane(self.table)
        osName = System.getProperty('os.name').lower()

        if not System.getProperty('java.specification.version')[-1] == '5':
            self.table.setFillsViewportHeight(True)
        pane.add(scrollPane, BorderLayout.CENTER)

        buttonPane = JPanel()
        sll = JButton('Save loci list')
        sll.addActionListener(self)
        sll.setActionCommand('SLL')
        buttonPane.add(sll)
        sci = JButton('Save confidence intervals')
        sci.addActionListener(self)
        sci.setActionCommand('SCI')
        buttonPane.add(sci)
        close = JButton('Close')
        close.addActionListener(self)
        close.setActionCommand('Close')
        buttonPane.add(close)
        pane.add(buttonPane, BorderLayout.PAGE_END)

        self.pack()
示例#53
0
 def config(self):
     #from django.utils.safestring import mark_safe
     if ":" in self.locationId:
         xx = self.locationId.split(":")
     ip = xx[0]
     port = xx[1]
     if self.devType == 1:
         #output = """<a href="javascript:cfg('%s', %s);">参数配置</a>"""
         output = u"""<a href="javascript:cfg('%s', %s);">参数配置</a>""" % (ip, port)
     elif self.devType == 2:
         from java.lang import System
         if System.getProperty("STATIC_ROOT", None):
             output = u"""<a href="/GokuCtrl/img_config/%s;">参数配置</a>""" % (self.uuid)
         else:
             output = u"""<a href="/img_config/%s;">参数配置</a>""" % (self.uuid)
     return output
示例#54
0
def loadModel():
    model = caseData.getCaseObject('nsfw_model')
    if model is None:
        file = System.getProperty('iped.root') + '/models/nsfw-keras-1.0.0.h5'
        from keras.models import load_model
        model = load_model(file)
        x = np.zeros((1, 224, 224, 3))
        #compile predict function to be used by multiple threads
        model.predict(x)
        caseData.putCaseObject('nsfw_model', model)
        logger.info('Loaded NSFW model ' + file)
        from java.util.concurrent import ConcurrentHashMap
        cache = ConcurrentHashMap()
        caseData.putCaseObject('nsfw_score_cache', cache)

    return model
示例#55
0
def getEnvar(envar):
    result = System.getProperty(envar)
    try:
        _excp_ = 0
        import os

        if result is None or result == "":
            result = os.environ[envar]
    except:
        _type_, _value_, _tbck_ = sys.exc_info()
        _excp_ = 1
        #endTry
    temp = _excp_
    if result is None:
        result = ""
    return result
示例#56
0
 def getLabel(self, jsonFile, key, listKey, valKey, labelKey):
     value = self.metadata.get(key)
     jsonLabelFile = System.getProperty("fascinator.home") + jsonFile
     jsonLabel = JsonSimple(File(jsonLabelFile))
     entries = jsonLabel.getJsonArray()
     # the structure of the json file is fun and complicated
     if entries is None:
         entries = jsonLabel.getArray(listKey)
     else:
         valKey = "value"
         labelKey = "label"
     for entry in entries:
         entryJson = JsonSimple(entry)
         if value == entryJson.getString("", valKey):
             return entryJson.getString("", labelKey)
     return None
示例#57
0
def filetourl(file):
    # A Python port of James Clark's fileToURL from XMLTest.java.
    from java.io import File
    from java.net import URL
    from java.lang import System

    file = File(file).getAbsolutePath()
    sep = System.getProperty("file.separator")

    if sep != None and len(sep) == 1:
        file = file.replace(sep[0], '/')

    if len(file) > 0 and file[0] != '/':
        file = '/' + file

    return URL('file', None, file).toString()
def __load_experiment_data__():
    basename = sicsext.getBaseFilename()
    fullname = str(System.getProperty('sics.data.path') + '/' + basename)
    df.datasets.clear()
    ds = df[fullname]
    data = ds[str(data_name.value)]
    axis = ds[str(axis_name.value)]
    if data.size > axis.size:
        data = data[:axis.size]
    ds2 = Dataset(data, axes=[axis])
    ds2.title = ds.id
    ds2.location = fullname
    Plot1.set_dataset(ds2)
    Plot1.x_label = axis_name.value
    Plot1.y_label = str(data_name.value)
    Plot1.title = str(data_name.value) + ' vs ' + axis_name.value
    Plot1.pv.getPlot().setMarkerEnabled(True)
 def __init__(self, cliHome, xldHost, xldPort, xldSecure, xldContext,
              xldProxyHost, xldProxyPort, xldSocketTimeout, xldUserName,
              xldPassword, script, cliExecutable, options):
     self.cmdLine = CmdLine()
     self.osname = System.getProperty('os.name').lower()
     if self.osname.startswith('win'):
         cliExecutable = "%s\\bin\\%s.cmd" % (cliHome, cliExecutable)
     else:
         cliExecutable = "%s/bin/%s.sh" % (cliHome, cliExecutable)
     # End if
     self.cmdLine.addArgument(cliExecutable)
     self.cmdLine.addArgument('-quiet')
     if xldHost != "DEFAULT":
         self.cmdLine.addArgument('-host')
         self.cmdLine.addArgument(xldHost)
     if xldPort != "DEFAULT":
         self.cmdLine.addArgument('-port')
         self.cmdLine.addArgument(xldPort)
     if xldSecure:
         self.cmdLine.addArgument('-secure')
     if xldContext != "DEFAULT":
         self.cmdLine.addArgument('-context')
         self.cmdLine.addArgument(xldContext)
     if xldProxyHost != "DEFAULT":
         self.cmdLine.addArgument('-proxyHost')
         self.cmdLine.addArgument(xldProxyHost)
     if xldProxyPort != "DEFAULT":
         self.cmdLine.addArgument('-proxyPort')
         self.cmdLine.addArgument(xldProxyPort)
     if xldSocketTimeout != "DEFAULT":
         self.cmdLine.addArgument('-socketTimeout')
         self.cmdLine.addArgument(xldSocketTimeout)
     if xldUserName != "DEFAULT":
         self.cmdLine.addArgument('-username')
         self.cmdLine.addArgument(xldUserName)
     if xldPassword != "DEFAULT":
         self.cmdLine.addArgument('-password')
         self.cmdLine.addPassword(xldPassword)
     if options is not None:
         self.options = str(options)
     # End if
     self.script = script
     self.stdout = CapturingOverthereExecutionOutputHandler.capturingHandler(
     )
     self.stderr = CapturingOverthereExecutionOutputHandler.capturingHandler(
     )
示例#60
0
    def __initKeyMap(self):
        os_name = System.getProperty("os.name")
        if os_name.startswith("Win"):
            exit_key = KeyEvent.VK_Z
            interrupt_key = KeyEvent.VK_PAUSE  # BREAK
        else:
            exit_key = KeyEvent.VK_D
            interrupt_key = KeyEvent.VK_C

        keyBindings = [
            (KeyEvent.VK_ENTER, 0, "jython.enter", self.enter),
            (KeyEvent.VK_DELETE, 0, "jython.delete", self.delete),
            (KeyEvent.VK_HOME, 0, "jython.home", self.home),
            (KeyEvent.VK_LEFT, InputEvent.META_DOWN_MASK, "jython.home",
             self.home),
            (KeyEvent.VK_UP, 0, "jython.up", self.history.historyUp),
            (KeyEvent.VK_DOWN, 0, "jython.down", self.history.historyDown),
            (KeyEvent.VK_PERIOD, 0, "jython.showPopup", self.showPopup),
            (KeyEvent.VK_ESCAPE, 0, "jython.hide", self.hide),
            ('(', 0, "jython.showTip", self.showTip),
            (')', 0, "jython.hideTip", self.hideTip),
            (exit_key, InputEvent.CTRL_MASK, "jython.exit", self.quit),
            (KeyEvent.VK_SPACE, InputEvent.CTRL_MASK, "jython.showPopup",
             self.showPopup),
            (KeyEvent.VK_SPACE, 0, "jython.space", self.spaceTyped),

            # explicitly set paste since we're overriding functionality
            (KeyEvent.VK_V,
             Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(),
             "jython.paste", self.paste),

            # Mac/Emacs keystrokes
            (KeyEvent.VK_A, InputEvent.CTRL_MASK, "jython.home", self.home),
            (KeyEvent.VK_E, InputEvent.CTRL_MASK, "jython.end", self.end),
            (KeyEvent.VK_K, InputEvent.CTRL_MASK, "jython.killToEndLine",
             self.killToEndLine),
            (KeyEvent.VK_Y, InputEvent.CTRL_MASK, "jython.paste", self.paste),
            (interrupt_key, InputEvent.CTRL_MASK, "jython.keyboardInterrupt",
             self.keyboardInterrupt),
        ]

        keymap = JTextComponent.addKeymap("jython", self.text_pane.keymap)
        for (key, modifier, name, function) in keyBindings:
            keymap.addActionForKeyStroke(KeyStroke.getKeyStroke(key, modifier),
                                         ActionDelegator(name, function))
        self.text_pane.keymap = keymap