### Index Installation Output Source: https://jython.readthedocs.io/en/latest/JythonDjango Example output showing the installation of database indexes. ```text Installing index for auth.Permission model Installing index for auth.Message model Installing index for polls.Choice model ``` -------------------------------- ### Setuptools Installation Output Source: https://jython.readthedocs.io/en/latest/appendixA Example output showing the successful installation of setuptools and the easy_install script. ```text Downloading http://pypi.python.org/packages/2.5/s/setuptools/setuptools-0.6c9-py2.5.egg Processing setuptools-0.6c9-py2.5.egg Copying setuptools-0.6c9-py2.5.egg to /home/lsoto/jython2.5.0/Lib/site-packages Adding setuptools 0.6c9 to easy-install.pth file Installing easy_install script to /home/lsoto/jython2.5.0/bin Installing easy_install-2.5 script to /home/lsoto/jython2.5.0/bin Installed /home/lsoto/jython2.5.0/Lib/site-packages/setuptools-0.6c9-py2.5.egg Processing dependencies for setuptools==0.6c9 Finished processing dependencies for setuptools==0.6c9 ``` -------------------------------- ### Installation Output for python-twitter Source: https://jython.readthedocs.io/en/latest/appendixA Example output showing the execution of setup.py and the installation of the python-twitter package. ```text Running python-twitter-0.6/setup.py -q bdist_egg --dist-dir /var/folders/mQ/mQkMNKiaE583pWpee85FFk+++TI/-Tmp-/easy_install-FU5COZ/python-twitter-0.6/egg-dist-tmp-EeR4RD zip_safe flag not set; analyzing archive contents... Unable to analyze compiled code on this platform. Please ask the author to include a 'zip_safe' setting (either True or False) in the package's setup.py Adding python-twitter 0.6 to easy-install.pth file Installed /home/lsoto/jython2.5.0/Lib/site-packages/python_twitter-0.6-py2.5.egg ``` -------------------------------- ### Package Installation Output Source: https://jython.readthedocs.io/en/latest/appendixA Example output demonstrating the automated installation of a package and its dependencies via easy_install. ```text Searching for python-twitter Reading http://pypi.python.org/simple/python-twitter/ Reading http://code.google.com/p/python-twitter/ Best match: python-twitter 0.6 Downloading http://python-twitter.googlecode.com/files/python-twitter-0.6.tar.gz Processing python-twitter-0.6.tar.gz Running python-twitter-0.6/setup.py -q bdist_egg --dist-dir /var/folders/mQ/mQkMNKiaE583pWpee85FFk+++TI/-Tmp-/easy_install-FU5COZ/python-twitter-0.6/egg-dist-tmp-EeR4RD zip_safe flag not set; analyzing archive contents... Unable to analyze compiled code on this platform. Please ask the author to include a 'zip_safe' setting (either True or False) in the package's setup.py Adding python-twitter 0.6 to easy-install.pth file Installed /home/lsoto/jython2.5.0/Lib/site-packages/python_twitter-0.6-py2.5.egg Processing dependencies for python-twitter Searching for simplejson Reading http://pypi.python.org/simple/simplejson/ Reading http://undefined.org/python/#simplejson Best match: simplejson 2.0.9 Downloading http://pypi.python.org/packages/source/s/simplejson/simplejson-2.0.9.tar.gz#md5=af5e67a39ca3408563411d357e6d5e47 Processing simplejson-2.0.9.tar.gz Running simplejson-2.0.9/setup.py -q bdist_egg --dist-dir /var/folders/mQ/mQkMNKiaE583pWpee85FFk+++TI/-Tmp-/easy_install-VgAKxa/simplejson-2.0.9/egg-dist-tmp-jcntqu *************************************************************************** WARNING: The C extension could not be compiled, speedups are not enabled. Failure information, if any, is above. I'm retrying the build without the C extension now. *************************************************************************** *************************************************************************** WARNING: The C extension could not be compiled, speedups are not enabled. Plain-Python installation succeeded. *************************************************************************** Adding simplejson 2.0.9 to easy-install.pth file Installed /home/lsoto/jython2.5.0/Lib/site-packages/simplejson-2.0.9-py2.5.egg Finished processing dependencies for python-twitter ``` -------------------------------- ### Full SQLAlchemy Setup and Data Operations Source: https://jython.readthedocs.io/en/latest/DatabasesAndJython A complete example demonstrating SQLAlchemy setup with zxoracle, including engine creation, metadata definition, table creation, class mapping, session management, adding player objects, and querying data. ```python import zxoracle from sqlalchemy import create_engine from sqlalchemy import Table, Column, String, Integer, MetaData, Sequence from sqlalchemy.orm import mapper, sessionmaker # Create engine db = create_engine('zxoracle://schema:password@hostname:port/database') # Create metadata and table metadata = MetaData() player_table = Table('player', metadata, Column('id', Integer, Sequence('id_seq'), primary_key=True), Column('first', String(50)), Column('last', String(50)), Column('position', String(30))) metadata.create_all(db) # Create class to hold table object class Player(object): def __init__(self, first, last, position): self.first = first self.last = last self.position = position def __repr__(self): return "" % (self.first, self.last, self.position) # Create mapper to map the table to the class mapper(Player, player_table) # Create Session class and bind it to the database Session = sessionmaker(bind=db) session = Session() # Create player objects, add them to the session player1 = Player('Josh', 'Juneau', 'forward') player2 = Player('Jim', 'Baker', 'forward') player3 = Player('Frank', 'Wierzbicki', 'defense') player4 = Player('Leo', 'Soto', 'defense') player5 = Player('Vic', 'Ng', 'center') session.add(player1) session.add(player2) session.add(player3) session.add(player4) session.add(player5) # Query the objects forwards = session.query(Player).filter_by(position='forward').all() print forwards defensemen = session.query(Player).filter_by(position='defense').all() print defensemen center = session.query(Player).filter_by(position='center').all() print center ``` -------------------------------- ### Install Setuptools Source: https://jython.readthedocs.io/en/latest/appendixA Execute the ez_setup.py script to install setuptools into the Jython environment. ```bash $ jython ez_setup.py ``` -------------------------------- ### Setup Environment and Install Nose with Jython Source: https://jython.readthedocs.io/en/latest/TestingIntegration This script configures the Python environment for Jython, downloads and installs setuptools (ez_setup), and then installs the Nose testing framework if it's not already present. It ensures that Nose is available for running tests within the Hudson build process. ```python # Setup the environment import os, sys, site, urllib2, tempfile print "Base dir", os.getcwdu() site_dir = os.path.join(os.getcwd(), 'site-packages') if not os.path.exists(site_dir): os.mkdir(site_dir) site.addsitedir(site_dir) sys.executable = '' os.environ['PYTHONPATH'] = ':'.join(sys.path) # Get ez_setup: ez_setup_path = os.path.join(site_dir, 'ez_setup.py') if not os.path.exists(ez_setup_path): f = file(ez_setup_path, 'w') f.write(urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py').read()) f.close() # Install nose if not present try: import nose except ImportError: import ez_setup ez_setup.main(['--install-dir', site_dir, 'nose']) for mod in sys.modules.keys(): if mod.startswith('nose'): del sys.modules[mod] for path in sys.path: if path.startswith(site_dir): sys.path.remove(site_dir) site.addsitedir(site_dir) import nose # Run Tests! nose.run(argv=['nosetests', '-v', '--with-doctest', '--with-xunit']) ``` -------------------------------- ### Install GlassFish Application Server Source: https://jython.readthedocs.io/en/latest/JythonDjango Execute the installer JAR file to begin the GlassFish installation. Ensure you have JDK6 installed. ```bash % java -Xmx256m -jar glassfish-installer-v2.1-b60e-windows.jar ``` -------------------------------- ### Install Django with setuptools Source: https://jython.readthedocs.io/en/latest/JythonDjango Use the easy_install command with setuptools to install a specific version of Django. Ensure the Jython bin directory is in your PATH. ```bash $ easy_install Django==1.0.3 ``` -------------------------------- ### Complete GlassFish Installation with Ant Source: https://jython.readthedocs.io/en/latest/JythonDjango Use Ant to finalize the GlassFish installation. This step is crucial for completing the setup. ```bash % chmod -R +x lib/ant/bin % lib/ant/bin/ant -f setup.xml ``` ```bash % lib\ant\bin\ant -f setup.xml ``` -------------------------------- ### Install Nose with easy_install Source: https://jython.readthedocs.io/en/latest/TestingIntegration Use this command to install the nose package via setuptools. ```bash $ easy_install nose ``` -------------------------------- ### Install a Package with easy_install Source: https://jython.readthedocs.io/en/latest/appendixA Use easy_install to download and install a Python library and its dependencies. ```bash $ easy_install python-twitter ``` -------------------------------- ### Install django-jython with setuptools Source: https://jython.readthedocs.io/en/latest/JythonDjango Install the django-jython package, which provides useful addons for running Django on Jython, including necessary database backends. ```bash $ easy_install django-jython ``` -------------------------------- ### Create and Start a Thread Source: https://jython.readthedocs.io/en/latest/Concurrency This snippet demonstrates the basic creation and starting of a thread. Ensure you pass a reference to the function object, not the result of calling it. ```python .. literalinclude:: src/chapter19/test_thread_creation.py ``` -------------------------------- ### Use Coroutine for File Searching Source: https://jython.readthedocs.io/en/latest/DefiningFunctionsandUsingBuilt-Ins This example demonstrates how to instantiate and use the `search_file` coroutine. It shows initializing the coroutine with a filename, priming it, and then sending search terms to get match counts. ```python >>> search = search_file("example4_3.txt") >>> search.next() Searching file example4_3.txt >>> search.send('python') Number of matches: 0 >>> search.send('Jython') Number of matches: 1 >>> search.send('the') Number of matches: 4 >>> search.send('This') Number of matches: 2 >>> search.close(); ``` -------------------------------- ### Application Entry Point Source: https://jython.readthedocs.io/en/latest/JythonIDE Initializes the application, opens the player data shelve, and starts the selection loop. ```python if __name__ == "__main__": print sys.path print "Hockey Roster Application\n\n" playerData = shelve.open("players") makeSelection() ``` -------------------------------- ### Dependency Installation Output Source: https://jython.readthedocs.io/en/latest/appendixA Output showing the installation of simplejson, including warnings regarding C extension compilation in Jython. ```text Processing simplejson-2.0.9.tar.gz Running simplejson-2.0.9/setup.py -q bdist_egg --dist-dir /var/folders/mQ/mQkMNKiaE583pWpee85FFk+++TI/-Tmp-/easy_install-VgAKxa/simplejson-2.0.9/egg-dist-tmp-jcntqu *************************************************************************** WARNING: The C extension could not be compiled, speedups are not enabled. Failure information, if any, is above. I'm retrying the build without the C extension now. *************************************************************************** *************************************************************************** WARNING: The C extension could not be compiled, speedups are not enabled. Plain-Python installation succeeded. *************************************************************************** Adding simplejson 2.0.9 to easy-install.pth file Installed /home/lsoto/jython2.5.0/Lib/site-packages/simplejson-2.0.9-py2.5.egg ``` -------------------------------- ### Install Specific Package Version Source: https://jython.readthedocs.io/en/latest/appendixA Command to install a specific version of a library using easy_install. ```bash $ easy_install python-twitter==0.5 ``` -------------------------------- ### Install SQLAlchemy with Jython Source: https://jython.readthedocs.io/en/latest/DatabasesAndJython Use this command to install SQLAlchemy after downloading the package. Ensure you are in the SQLAlchemy directory in your terminal. ```bash jython setup.py install ``` -------------------------------- ### Main Application Entry Point Source: https://jython.readthedocs.io/en/latest/DatabasesAndJython Initializes the Hibernate session factory and starts the application loop. ```python if __name__ == "__main__": print "Hockey Roster Application\n\n" cfg = Configuration().configure() factory = cfg.buildSessionFactory() global runApp runApp = True while runApp: makeSelection() ``` -------------------------------- ### Start Django Project Source: https://jython.readthedocs.io/en/latest/JythonDjango Use this command to create a new Django project. Ensure you are in the desired parent directory. ```bash $ django-admin.py startproject pollsite ``` -------------------------------- ### Package Search Output Detail Source: https://jython.readthedocs.io/en/latest/appendixA A snippet of the output showing the initial search and download phase of the installation process. ```text Searching for python-twitter Reading http://pypi.python.org/simple/python-twitter/ Reading http://code.google.com/p/python-twitter/ Best match: python-twitter 0.6 Downloading http://python-twitter.googlecode.com/files/python-twitter-0.6.tar.gz ``` -------------------------------- ### Install Pylons Source: https://jython.readthedocs.io/en/latest/IntroToPylons Install the Pylons framework version 0.9.7 within a virtual environment. ```bash > easy_install "Pylons==0.9.7" ``` -------------------------------- ### Install virtualenv using easy_install Source: https://jython.readthedocs.io/en/latest/appendixA Use easy_install with Jython to install the virtualenv package from the Python Package Index. ```shell jython easy_install.py virtualenv ``` -------------------------------- ### Database Creation Output Source: https://jython.readthedocs.io/en/latest/JythonDjango Example output showing the creation of database tables during the synchronization process. ```text Creating table auth_permission Creating table auth_group Creating table auth_user Creating table auth_message Creating table django_content_type Creating table django_session Creating table django_site Creating table polls_poll Creating table polls_choice You just installed Django's auth system, which means you don't have any superusers defined. Would you like to create one now? (yes/no): ``` -------------------------------- ### Run development server Source: https://jython.readthedocs.io/en/latest/JythonDjango Command to start the Django development server for testing. ```bash $ jython manage.py runserver ``` -------------------------------- ### Configure Build.xml for TaskContainer Source: https://jython.readthedocs.io/en/latest/appendixB Example build file demonstrating the usage of a custom task container. ```xml ``` -------------------------------- ### Launch Development Server Source: https://jython.readthedocs.io/en/latest/IntroToPylons Start the Pylons development server with auto-reload enabled. ```bash > paster serve --reload development.ini ``` -------------------------------- ### Start GlassFish Application Server Source: https://jython.readthedocs.io/en/latest/JythonDjango Invoke the asadmin command to start the GlassFish domain. The server will run in the foreground on Windows and daemonize on UNIX. ```bash % bin/asadmin start_domain -v ``` -------------------------------- ### Pylons Interactive Shell Example Source: https://jython.readthedocs.io/en/latest/IntroToPylons An example of the Pylons interactive shell output, showing available objects and how to make a request and inspect the response. ```python Pylons Interactive Shell Jython 2.5.0 (Release_2_5_0:6476, Jun 16 2009, 13:33:26) [OpenJDK Server VM (Sun Microsystems Inc.)] All objects from rostertool.lib.base are available Additional Objects: mapper - Routes mapper object wsgiapp - This project's WSGI App instance app - paste.fixture wrapped around wsgiapp >>> resp = app.get('/roster/index') >>> resp >>> resp.req ``` -------------------------------- ### Example XML File Source: https://jython.readthedocs.io/en/latest/appendixB This XML file serves as sample data for the Jython log4j example. The script reads this file; any text file can be used by modifying the 'open' call in the script. ```xml W I TU Cathrine Knight 34-5424-77 10/12/1938
4780 Centerville Saint Paul, MN 55127
``` -------------------------------- ### Example Script: builder.py Source: https://jython.readthedocs.io/en/latest An example script demonstrating Jython's capabilities. This snippet is part of the 'Scripting With Jython' chapter. ```python import sys def main(argv=sys.argv): print 'Hello, world!' print 'Arguments:' for arg in argv: print ' - %s' % arg if __name__ == '__main__': main() ``` -------------------------------- ### Create Static HTML File Source: https://jython.readthedocs.io/en/latest/IntroToPylons Example of a static HTML file to be placed in the public directory. ```html Just a static file ``` -------------------------------- ### Start Pylons in Development Mode Source: https://jython.readthedocs.io/en/latest/IntroToPylons Launch the application with automatic code reloading enabled. ```bash $ paster serve development.ini --reload ``` -------------------------------- ### Java Print Output Example Source: https://jython.readthedocs.io/en/latest/LangSyntax This is the Java equivalent of printing a line of text to the command line. ```java System.out.println("This text will be printed to the command line"); ``` -------------------------------- ### Installation Completion Message Source: https://jython.readthedocs.io/en/latest/appendixA Final output indicating the completion of the dependency processing. ```text Finished processing dependencies for python-twitter ``` -------------------------------- ### View Doctest Execution Output Source: https://jython.readthedocs.io/en/latest/JythonIDE/#netbeans Example output showing the results of running the doctest module. ```text Trying: from hello import console Expecting nothing ok Trying: console.print_message("testing") Expecting: testing ok 1 items passed all tests: 2 tests in __main__ 2 tests in 1 items. 2 passed and 0 failed. Test passed. ``` -------------------------------- ### Verify SQLAlchemy Installation in Jython Source: https://jython.readthedocs.io/en/latest/DatabasesAndJython After installation, import the sqlalchemy module and check its version to confirm successful setup. This verifies that SQLAlchemy is accessible within your Jython environment. ```python >>> import sqlalchemy >>> sqlalchemy.__version__ '0.6beta1' >>> ``` -------------------------------- ### Synchronize with threading.Lock Source: https://jython.readthedocs.io/en/latest/Concurrency Examples demonstrating the use of threading.Lock for synchronization, comparing the recommended with-statement approach against the try-finally pattern. ```python .. literalinclude:: src/chapter19/test_lock.py :pyobject: LockTestCase.test_with_lock ``` ```python .. literalinclude:: src/chapter19/test_lock.py :pyobject: LockTestCase.test_try_finally_lock ``` -------------------------------- ### Use Range Function Source: https://jython.readthedocs.io/en/latest/DataTypes Examples of generating numeric sequences with various start, stop, and step parameters. ```python #Simple range starting with zero, note that the end point is not included in the range >>>range(0,10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(50, 65) [50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64] >>>range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Include a step of two in the range >>>range(0,10,2) [0, 2, 4, 6, 8] # Including a negative step performs the same functionality...the step is added to the previously # number in the range >>> range(100,0,-10) [100, 90, 80, 70, 60, 50, 40, 30, 20, 10] ``` -------------------------------- ### Start the SDK web server Source: https://jython.readthedocs.io/en/latest/DeploymentTargets Run this command from the terminal within the Google App Engine SDK directory to launch the local development server for the guestbook demo. ```bash /bin/dev_appserver.sh demos/guestbook/war ``` -------------------------------- ### Iterate with Index using enumerate Source: https://jython.readthedocs.io/en/latest/appendixC Use enumerate to get both the index and value when iterating over a sequence. The start parameter can be used to set the initial index. ```python for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter']): print i, season ``` -------------------------------- ### Test Module: test_lists.py Source: https://jython.readthedocs.io/en/latest/TestingIntegration Organize tests into separate modules for better maintainability. This example demonstrates a test class for list operations using `setUp` for initialization. ```python import unittest class TestLists(unittest.TestCase): def setUp(self): self.list = ['foo', 'bar', 'baz'] def testLen(self): self.assertEqual(3, len(self.list)) def testContains(self): self.assert_('foo' in self.list) self.assert_('bar' in self.list) self.assert_('baz' in self.list) def testSort(self): self.assertNotEqual(['bar', 'baz', 'foo'], self.list) self.list.sort() self.assertEqual(['bar', 'baz', 'foo'], self.list) ``` -------------------------------- ### Implement searchdir.py entry point Source: https://jython.readthedocs.io/en/latest/ModulesPackages Main script to initiate directory scanning based on command line arguments. ```python import search.scanner as scanner import sys help = """ Usage: search.py directory terms... """ args = sys.argv if args == None or len(args) < 2: print help exit() dir = args[1] terms = args[2:] scan = scanner.scan(dir, terms) scan.display() ``` -------------------------------- ### Basic Unittest TestCase for Math Functions Source: https://jython.readthedocs.io/en/latest/TestingIntegration Subclass unittest.TestCase and define test methods starting with 'test'. Use assertion methods like assertEqual to verify expected outcomes. Setup and teardown methods can be overridden for pre/post-test actions. ```python import math import unittest class TestMath(unittest.TestCase): def testFloor(self): self.assertEqual(1, math.floor(1.01)) self.assertEqual(0, math.floor(0.5)) self.assertEqual(-1, math.floor(-0.5)) self.assertEqual(-2, math.floor(-1.1)) def testCeil(self): self.assertEqual(2, math.ceil(1.01)) self.assertEqual(1, math.ceil(0.5)) self.assertEqual(0, math.ceil(-0.5)) self.assertEqual(-1, math.ceil(-1.1)) ``` -------------------------------- ### Execute Main Application Source: https://jython.readthedocs.io/en/latest/JythonAndJavaIntegration Demonstrates using the BuildingFactory to instantiate and print building information. ```java package org.jython.book; import org.jython.book.util.BuildingFactory; import org.jython.book.interfaces.BuildingType; public class Main { private static void print(BuildingType building) { System.out.println("Building Info: " + building.getBuildingId() + " " + building.getBuildingName() + " " + building.getBuildingAddress()); } public static void main(String[] args) { BuildingFactory factory = new BuildingFactory(); print(factory.create("BUILDING-A", "100 WEST MAIN", "1")); print(factory.create("BUILDING-B", "110 WEST MAIN", "2")); print(factory.create("BUILDING-C", "120 WEST MAIN", "3")); } } ``` -------------------------------- ### Install python-twitter Package Source: https://jython.readthedocs.io/en/latest/GUIApplications Use easy_install to install the python-twitter package and its dependencies. ```bash jython easy_install python-twitter ``` -------------------------------- ### sum(iterable[, start]) Source: https://jython.readthedocs.io/en/latest/appendixC Sums start and the items of an iterable from left to right. ```APIDOC ## sum(iterable[, start]) ### Description Sums start and the items of an iterable from left to right and returns the total. ### Parameters - **iterable** (iterable) - Required - The collection of numbers to sum. - **start** (number) - Optional - The value to start the sum from (defaults to 0). ``` -------------------------------- ### Install yolk utility Source: https://jython.readthedocs.io/en/latest/appendixA Install the yolk utility using ez_install.py. This utility is used to list installed packages within a Jython environment. Requires Jython 2.5.1 or later and JDK 1.6+. ```shell jython ez_install.py yolk ``` -------------------------------- ### Initialize Django Database Source: https://jython.readthedocs.io/en/latest/JythonDjango Runs the syncdb command to create tables and set up the initial superuser account. ```bash > > jython manage.py syncdb Creating table django_admin_log Creating table auth_permission Creating table auth_group Creating table auth_user Creating table auth_message Creating table django_content_type Creating table django_session Creating table django_site > You just installed Django’s auth system, which means you don’t have any superusers defined. Would you like to create one now? (yes/no): yes Username: admin E-mail address: admin@abc.com Warning: Problem with getpass. Passwords may be echoed. Password: admin Warning: Problem with getpass. Passwords may be echoed. Password (again): admin Superuser created successfully. Installing index for admin.LogEntry model Installing index for auth.Permission model Installing index for auth.Message model ``` -------------------------------- ### Start Django App Source: https://jython.readthedocs.io/en/latest/JythonDjango Create a new Django app within your project. Ensure you are in the project's root directory. ```bash $ jython manage.py startapp polls ``` -------------------------------- ### Main Application Entry Point Source: https://jython.readthedocs.io/en/latest/JythonIDE Handles command-line arguments for UI selection and language settings, with error handling for unsupported inputs. ```python import sys import hello, hello.console, hello.window from optparse import OptionParser def main(args): parser = OptionParser() parser.add_option('--ui', dest='ui', default='console', help="Sets the UI to use to greet the user. One of: %s" % ", ".join("'%s'" % ui for ui in list_uis())) parser.add_option('--lang', dest='lang', default='en', help="Sets the language to use") options, args = parser.parse_args(args) if len(args) < 2: print "Sorry, I can't greet you if you don't say your name" return 1 try: hello.greet(args[1], options.lang, options.ui) except hello.LanguageNotSupportedException: print "Sorry, I don't speak '%s'" % options.lang return 1 except hello.UINotSupportedExeption: print "Invalid UI name\n" print "Valid UIs:\n\n" + "\n".join(' * ' + ui for ui in hello.list_uis()) return 1 return 0 if __name__ == "__main__": main(sys.argv) ``` -------------------------------- ### Install and Build WAR with snakefight Source: https://jython.readthedocs.io/en/latest/IntroToPylons Commands to install the snakefight package and generate a WAR file for a Jython application. ```bash $ easy_install snakefight ...snakefight will download and install here ... $ jython setup.py bdist_war --paste-config test.ini ``` -------------------------------- ### Connect to Database with Runtime CLASSPATH Loading Source: https://jython.readthedocs.io/en/latest/appendixB Demonstrates attempting a standard database connection and falling back to a custom classPathHacker to load the driver if the initial attempt fails. ```python import sys from com.ziclix.python.sql import zxJDBC d,u,p,v = "jdbc:postgresql://localhost/img_arc2","postgres","","org.postgresql.Driver" try : # if called from command line with .login CLASSPATH setup right,this works db = zxJDBC.connect(d, u, p, v) except: # if called from Apache or account where the .login has not set CLASSPATH # need to use run-time CLASSPATH Hacker try : jarLoad = classPathHacker() a = jarLoad.addFile("/usr/share/java/postgresql-jdbc3.jar") db = zxJDBC.connect(d, u, p, v) except : sys.exit ("still failed \n%s" % (sys.exc_info() )) ``` -------------------------------- ### Display documentation for a function Source: https://jython.readthedocs.io/en/latest/LangSyntax This example shows how to use the built-in 'help()' function to retrieve and display the docstring for a specific function, in this case, 'tip_calc'. ```python help(tip_calc) ``` -------------------------------- ### Create and Initialize a Set Source: https://jython.readthedocs.io/en/latest/DataTypes Demonstrates how to import the `Set` class and create a set with initial elements. Sets are unordered collections of unique elements. ```python # In order to use a Set, we must first import it >>> from sets import Set # To create a set use the following syntax >>> myset = Set([1,2,3,4,5]) >>> myset Set([5, 3, 2, 1, 4]) ``` -------------------------------- ### Verify Django and django-jython installation Source: https://jython.readthedocs.io/en/latest/JythonDjango Import the top-level packages of Django and django-jython in the Jython interpreter to confirm a successful installation. No errors should be printed. ```python >>> import django >>> import doj ``` -------------------------------- ### Start STOMP Connector Source: https://jython.readthedocs.io/en/latest/JythonDjango Command to start the STOMP connector, bridging JMS and STOMP. Ensure all necessary JAR files are in the lib directory. ```bash java -cp "lib\*;stompconnect-1.0.jar" \ org.codehaus.stomp.jms.Main tcp://0.0.0.0:6666 \ "jms/MyConnectionFactory" ``` -------------------------------- ### File Handling with Contextlib Source: https://jython.readthedocs.io/en/latest/ObjectOrientedJython Demonstrates basic file writing and reading using `contextlib.closing` for automatic resource management. Ensure `__future__.with_statement` is imported for compatibility. ```python from __future__ import with_statement from contextlib import closing with closing(open(‘simplefile’,’w’)) as fout: fout.writelines([“blah”]) with closing(open(‘simplefile’,’r’)) as fin: print fin.readlines() ``` -------------------------------- ### Connect to a database using zxJDBC Source: https://jython.readthedocs.io/en/latest/DatabasesAndJython Demonstrates connecting to an Oracle database using the context manager for automatic resource handling. ```python jdbc_url = "jdbc:oracle:thin:@host:port:sid" username = "world" password = "world" driver = "oracle.jdbc.driver.OracleDriver" with zxJDBC.connect(jdbc_url, username, password, driver) as conn: with conn.cursor() as c: c.execute("select * from emp") for row in islice(c, 20): print row # let's redo this w/ namedtuple momentarily... ``` -------------------------------- ### Python Expression Examples Source: https://jython.readthedocs.io/en/latest/LangSyntax Shows examples of simple expressions involving arithmetic operators. Expressions are combinations of values and operators that evaluate to a value. ```python >>> x + y >>> x - y >>> x * y >>> x / y ``` -------------------------------- ### Configure Media Settings for WAR Deployment Source: https://jython.readthedocs.io/en/latest/JythonDjango Set MEDIA_ROOT and MEDIA_URL in your settings.py to properly serve static files when deploying as a WAR file. Ensure the MEDIA_ROOT directory exists and contains sample files. ```python MEDIA_ROOT = ‘c:\\dev\\hello\\media_root’ MEDIA_URL = ‘/site_media/’ ``` -------------------------------- ### Accessing GET Parameters in Pylons Source: https://jython.readthedocs.io/en/latest/IntroToPylons Demonstrates how Pylons handles GET parameters, including multiple values for the same key, and how to retrieve them using `req.GET`. ```python >>> resp = app.get('/roster/index?foo=bar&x=42&x=50') >>> resp.req.GET UnicodeMultiDict([('foo', u'bar'), ('x', u'42'), ('x', u'50')]) >>> req.GET['x'] u'50' >>> req.GET.getall('x') [u'42', u'50'] ``` -------------------------------- ### Custom Assertion Method Example Source: https://jython.readthedocs.io/en/latest/TestingIntegration Define custom assertion methods to extend unittest's capabilities. This example shows how to create an `assertGreaterThan` method. ```python class SomeTestCase(unittest.TestCase): def assertGreaterThan(a, b): self.assert_(a > b, '%d isn\'t greater than %d') def testSomething(self): self.assertGreaterThan(10, 4) ``` -------------------------------- ### Get Object's Symbol Table Source: https://jython.readthedocs.io/en/latest/appendixC Pass an object with a __dict__ attribute to vars() to get its symbol table. Modifying the returned dictionary is not recommended. ```python vars(module_or_class_or_instance) ``` -------------------------------- ### Create PostgreSQL Database Source: https://jython.readthedocs.io/en/latest/JythonDjango Uses the createdb command to initialize a new database instance. ```bash > createdb demodb ``` -------------------------------- ### List installed packages with yolk Source: https://jython.readthedocs.io/en/latest/appendixA Use the yolk -l command to list all installed packages within the current Jython environment, including their versions and status. ```shell yolk -l ``` -------------------------------- ### Define and instantiate a Python class Source: https://jython.readthedocs.io/en/latest/LangSyntax Demonstrates defining a class with an __init__ initializer and custom methods, then instantiating it and calling those methods. ```python >>> class my_object: ... def __init__(self, x, y): ... self.x = x ... self.y = y ... ... def mult(self): ... print self.x * self.y ... ... def add(self): ... print self.x + self.y ... >>> obj1 = my_object(7, 8) >>> obj1.mult() 56 >>> obj1.add() 15 ``` -------------------------------- ### Get Unicode code point of a character Source: https://jython.readthedocs.io/en/latest/appendixC Use `ord()` to get the integer Unicode code point for a single character string. This is the inverse of `chr()` or `unichr()`. ```python ord('a') ``` ```python ord(u'\u2020') ``` -------------------------------- ### Lambda Function Example: Combine Strings Source: https://jython.readthedocs.io/en/latest/DefiningFunctionsandUsingBuilt-Ins This example demonstrates assigning a lambda function to a variable to combine first and last names. Lambda functions return a value implicitly. ```python >>> name_combo = lambda first, last: first + ' ' + last >>> name_combo('Jim','Baker') 'Jim Baker' ``` -------------------------------- ### Basic 'Hello World' in Jython Source: https://jython.readthedocs.io/en/latest/JythonIDE This is a simple 'Hello World' program written in Jython. It demonstrates the basic structure of a Python script and how to print output to the console. Ensure the script is saved as a module and executed within the PyDev environment. ```python if __name__ == "__main__": print "Hello PyDev!" ``` -------------------------------- ### Execute Build Script Commands Source: https://jython.readthedocs.io/en/latest/Scripting Example command-line interactions with the builder.py script to list tasks, compile code, and clean directories. ```bash [frank@pacman chapter8]$ jython builder.py --help Usage: builder.py [options] Options: -h, --help show this help message and exit -q, --quiet Don't print out task messages. -p, --projecthelp Print out list of tasks. [frank@pacman chapter8]$ jython builder.py --projecthelp compile clean [frank@pacman chapter8]$ jython builder.py compile compiling ['HelloWorld.java'] compiled [frank@pacman chapter8]$ ls DEBUG.classicHelloWorld.java HelloWorld.classicHelloWorldbuilder.py [frank@pacman chapter8]$ jython builder.py clean [frank@pacman chapter8]$ ls HelloWorld.javabuilder.py [frank@pacman chapter8]$ jython builder.py --quiet compile [frank@pacman chapter8]$ ls DEBUG.classicHelloWorldHelloWorld.java HelloWorld.classicHelloWorldHelloWorldbuilder.py [frank@pacman chapter8]$ ``` -------------------------------- ### Generate JNLP File for Web Start Application Source: https://jython.readthedocs.io/en/latest/SimpleWebApps This XML file is used to launch a Jython application via Java Web Start. Ensure the codebase and jar href attributes are correctly set for your application structure. ```xml JythonSwingApp YourName JythonSwingApp JythonSwingApp ``` -------------------------------- ### Command Line Execution Example Source: https://jython.readthedocs.io/en/latest/TestingIntegration Execute your test file using the Jython interpreter from the command line. This command will run all tests defined in the specified file. ```bash $ jython test_math.py ``` -------------------------------- ### Initialize FeedWriter Module Source: https://jython.readthedocs.io/en/latest/appendixB The starting boilerplate for a FeedWriter module. ```python ######################################## # File: FeedReader.py # ``` -------------------------------- ### Create and Write XML with ElementTree Source: https://jython.readthedocs.io/en/latest/appendixB Demonstrates building an XML structure in memory and writing it to a file or standard output. ```python from elementtree import ElementTree as ET root = ET.Element("html") head = ET.SubElement(root, "head") title = ET.SubElement(head, "title") title.text = "Page Title" body = ET.SubElement(root, "body") body.set("bgcolor", "#ffffff") body.text = "Hello, World!" tree = ET.ElementTree(root) tree.write("page.xhtml") import sys tree.write(sys.stdout) ``` ```html Page TitleHello, World! ``` -------------------------------- ### Hello World in PyDev Source: https://jython.readthedocs.io/en/latest/JythonIDE/#netbeans A basic Python script to demonstrate module execution within the PyDev environment. ```python if __name__ == "__main__": print "Hello PyDev!" ``` -------------------------------- ### Augmented Assignment Example Source: https://jython.readthedocs.io/en/latest/OpsExpressPF Demonstrates the use of the multiplication augmented assignment operator. ```python >>> x*=5 >>> x 30 ```