### Setuptools Installation Output Source: https://github.com/jython/book/blob/master/appendixA.rst This output shows the successful installation of setuptools and the easy_install script, including its location within the Jython installation directory. ```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 ``` -------------------------------- ### Install Nose using easy_install Source: https://github.com/jython/book/blob/master/TestingIntegration.rst Install the Nose testing framework using the easy_install command. Ensure setuptools is installed first. ```bash $ easy_install nose ``` -------------------------------- ### Install Setuptools with Jython Source: https://github.com/jython/book/blob/master/appendixA.rst Execute the ez_setup.py script using Jython to install setuptools. Ensure the Jython bin directory is in your PATH for easier access to installed scripts. ```shell $ jython ez_setup.py ``` -------------------------------- ### Install and Run Nose with Jython Source: https://github.com/jython/book/blob/master/TestingIntegration.rst This script sets up a local site-packages directory, downloads and installs setuptools (ez_setup), installs the Nose testing framework if not present, and then runs tests using Nose with doctest and xunit support. ```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']) ``` -------------------------------- ### Python raw_input() Example Source: https://github.com/jython/book/blob/master/LangSyntax.rst Demonstrates using raw_input() to get user input as a string. The optional prompt is displayed to the user. ```python name = raw_input("Enter Your Name:") print name ``` -------------------------------- ### Installing Glassfish Application Server Source: https://github.com/jython/book/blob/master/JythonDjango.rst Use this command to install Glassfish v2.1. Ensure you have JDK6 installed and run the command from the directory where you want Glassfish to be unpacked. ```shell java -Xmx256m -jar glassfish-installer-v2.1-b60e-windows.jar ``` -------------------------------- ### easy_install Output: Installation and Warnings Source: https://github.com/jython/book/blob/master/appendixA.rst This output details the installation process of 'python-twitter' and 'simplejson', including warnings about C extension compilation failures specific to Jython. ```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 ``` ```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 ``` ```text Finished processing dependencies for python-twitter ``` -------------------------------- ### Install Python Package with Easy Install Source: https://github.com/jython/book/blob/master/appendixA.rst Use the easy_install command to automatically download and install a Python package and its dependencies. This example installs the python-twitter package. ```shell $ easy_install python-twitter ``` -------------------------------- ### Start Application Server Source: https://github.com/jython/book/blob/master/JythonDjango.rst Start the application server using the 'asadmin' command. This command will start the server in the foreground on Windows and in the background on UNIX. ```shell % bin/asadmin start_domain -v ``` -------------------------------- ### Java Print Output Example Source: https://github.com/jython/book/blob/master/LangSyntax.rst This is a Java example demonstrating how to print text to the command line. ```java System.out.println("This text will be printed to the command line"); ``` -------------------------------- ### Install RosterTool using easy_install Source: https://github.com/jython/book/blob/master/src/chapter15/RosterTool/README.txt Use this command to install the RosterTool package. Ensure easy_install is available in your environment. ```bash easy_install RosterTool ``` -------------------------------- ### Install Django with easy_install Source: https://github.com/jython/book/blob/master/JythonDjango.rst Use the easy_install command to install a specific version of Django. Ensure Jython's bin directory is in your PATH. ```bash $ easy_install Django==1.0.3 ``` -------------------------------- ### Python Print Output Example Source: https://github.com/jython/book/blob/master/LangSyntax.rst This Python example shows how to print a string to the console. ```python print 'This text will be printed to the command line' ``` -------------------------------- ### Test Case with setUp and Assertions in Python unittest Source: https://github.com/jython/book/blob/master/TestingIntegration.rst Demonstrates a test case with a setUp method for common initialization and various assertions including assertEqual, assert_, and assertNotEqual. ```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) ``` -------------------------------- ### Start Django Project Source: https://github.com/jython/book/blob/master/JythonDjango.rst Use this command to create a new Django project. Ensure you are in the desired parent directory. ```bash $ django-admin.py startproject pollsite ``` -------------------------------- ### Install django-jython with easy_install Source: https://github.com/jython/book/blob/master/JythonDjango.rst Install the django-jython package, which provides essential addons for running Django on Jython, including database backends. This command should be run after installing Django itself. ```bash $ easy_install django-jython ``` -------------------------------- ### Launch Jython Application with Java Web Start Source: https://github.com/jython/book/blob/master/SimpleWebApps.rst Use deployJava.createWebStartLaunchButton to create a button for launching a Java Web Start application. Ensure the URL points to your JNLP file. ```javascript var url="http://[fill in your URL]/launch.jnlp" deployJava.createWebStartLaunchButton(url, "1.6") ``` -------------------------------- ### Install snakefight Source: https://github.com/jython/book/blob/master/IntroToPylons.rst Use easy_install to install the snakefight package, which is necessary for building WAR files for deployment. ```bash $ easy_install snakefight ...snakefight will download and install here ... ``` -------------------------------- ### Run Ant Setup Script Source: https://github.com/jython/book/blob/master/JythonDjango.rst Execute the Ant setup script to prepare the project environment. Ensure the script has execute permissions. ```shell % chmod -R +x lib/ant/bin % lib/ant/bin/ant -f setup.xml ``` ```shell % lib\ant\bin\ant -f setup.xml ``` -------------------------------- ### Generate HTML Documentation Source: https://github.com/jython/book/blob/master/src/chapter15/RosterTool/docs/index.txt Run this command to generate documentation in HTML format. Ensure buildutils, pudge, and pygments are installed. ```bash setup.py pudge ``` -------------------------------- ### Install SQLAlchemy with Jython Source: https://github.com/jython/book/blob/master/DatabasesAndJython.rst Install SQLAlchemy using the provided setup.py script within your Jython environment. Ensure you are in the SQLAlchemy directory in your terminal. ```bash jython setup.py install ``` -------------------------------- ### Install Pylons using easy_install Source: https://github.com/jython/book/blob/master/IntroToPylons.rst Installs Pylons version 0.9.7 within a virtual environment. Ensure you have Jython set up. ```bash > easy_install "Pylons==0.9.7" ``` -------------------------------- ### Example XML File Structure Source: https://github.com/jython/book/blob/master/appendixB.rst This is a sample XML file structure. The Jython script can read and process any text file, but this provides an example of an XML format. ```XML W I TU Cathrine Knight 34-5424-77 10/12/1938
4780 Centerville Saint Paul, MN 55127
``` -------------------------------- ### Start STOMP Connector Source: https://github.com/jython/book/blob/master/JythonDjango.rst Command to start the STOMP connector, bridging to a JMS broker. Ensure all required JARs 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" ``` -------------------------------- ### Easy Install Output for Python-Twitter Source: https://github.com/jython/book/blob/master/appendixA.rst This output details the process of installing the python-twitter package, including dependency resolution and potential warnings about C extension compilation. ```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. ``` -------------------------------- ### JNLP Configuration for Web Start Source: https://github.com/jython/book/blob/master/SimpleWebApps.rst This JNLP file configures the application for deployment via Web Start. It specifies the application title, vendor, description, security permissions, and required resources including JRE and JAR files. ```XML JythonSwingApp YourName JythonSwingApp JythonSwingApp ``` -------------------------------- ### enumerate(sequence[, start=0]) Source: https://github.com/jython/book/blob/master/appendixC.rst Returns an enumerate object that iterates over a sequence, yielding pairs of count and value. The count starts from the optional 'start' parameter, which defaults to 0. Useful for getting an indexed series. ```APIDOC ## enumerate(sequence[, start=0]) ### Description Returns an enumerate object. The sequence must support iteration. The iterator yields tuples of (count, value). ### Method Built-in function ### Parameters - **sequence** (sequence, iterator, or iterable) - The object to iterate over. - **start** (integer, optional) - The starting value for the count. Defaults to 0. ### Request Example ```python for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter']): print i, season ``` ### Response - **enumerate object** - An iterator yielding (count, value) tuples. ### Version History - **2.3**: Added. - **2.6**: Added the `start` parameter. ``` -------------------------------- ### Slicing Lists to Get Subsets Source: https://github.com/jython/book/blob/master/DataTypes.rst Slice lists using `[start:end]` notation to extract a range of elements. The element at the `end` index is excluded. Omitting `start` defaults to 0, and omitting `end` defaults to the list's length. ```python >>> my_string_list[0:2] ['Hello', 'Jython'] ``` -------------------------------- ### Iterating with Index using enumerate Source: https://github.com/jython/book/blob/master/appendixC.rst Use enumerate to get both the index and value while iterating over a sequence. The 'start' parameter can be used to begin indexing from a number other than 0. ```Python for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter']): print i, season ``` -------------------------------- ### Jython Servlet Example Source: https://context7.com/jython/book/llms.txt A basic Jython HttpServlet that handles GET and POST requests, sets an attribute, and forwards to a JSP page. Ensure the 'p' parameter is provided in the request. ```python import java, javax class add_to_page(javax.servlet.http.HttpServlet): def doGet(self, request, response): self.doPost(request, response) def doPost(self, request, response): addtext = request.getParameter("p") if not addtext: addtext = "" request.setAttribute("page_text", addtext) dispatcher = request.getRequestDispatcher("testJython.jsp") dispatcher.forward(request, response) ``` -------------------------------- ### Verify SQLAlchemy Installation Source: https://github.com/jython/book/blob/master/DatabasesAndJython.rst After installation, verify that SQLAlchemy is accessible in Jython by importing it and checking its version. This confirms the installation was successful. ```python >>> import sqlalchemy >>> sqlalchemy.__version__ '0.6beta1' >>> ``` -------------------------------- ### Setup RosterTool Application Source: https://github.com/jython/book/blob/master/src/chapter15/RosterTool/README.txt Initializes the RosterTool application using the generated configuration file. This step is required after tweaking the config file. ```bash paster setup-app config.ini ``` -------------------------------- ### Routes Configuration Example Source: https://github.com/jython/book/blob/master/IntroToPylons.rst Illustrates how to define URL routes in Pylons using the Routes library, mapping URLs to controller actions. ```python map.connect('/', controller='roster', action='index') map.connect('/{action}/{id}/', controller='roster') map.connect('/add_player/', controller='roster', action='add_player') ``` -------------------------------- ### Verify Django and django-jython installation Source: https://github.com/jython/book/blob/master/JythonDjango.rst Import the top-level packages for Django and django-jython in Jython to confirm a successful installation. No errors should be printed if the installation was successful. ```python >>> import django >>> import doj ``` -------------------------------- ### easy_install Output: Searching and Downloading Source: https://github.com/jython/book/blob/master/appendixA.rst This output shows the steps easy_install takes to find and download the 'python-twitter' package and its dependency 'simplejson' from PyPI. ```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 ``` ```text 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 ``` -------------------------------- ### sum(iterable[, start]) Source: https://github.com/jython/book/blob/master/sandbox/builtins.rst Sums the items of an iterable with an optional starting value. ```APIDOC ## sum(iterable[, start]) ### Description Sums *start* and the items of an *iterable* from left to right and returns the total. *start* defaults to ``0``. The *iterable*'s items are normally numbers, and are not allowed to be strings. The fast, correct way to concatenate a sequence of strings is by calling ``''.join(sequence)``. Note that ``sum(range(n), m)`` is equivalent to ``reduce(operator.add, range(n), m)`` To add floating point values with extended precision, see :func:`math.fsum`. .. versionadded:: 2.3 ### Method N/A (Built-in function) ### Endpoint N/A (Built-in function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python numbers = [1, 2, 3, 4, 5] total = sum(numbers) print(total) # Output: 15 numbers_with_start = [1, 2, 3, 4, 5] total_with_start = sum(numbers_with_start, 10) print(total_with_start) # Output: 25 # Example of incorrect usage with strings # strings = ['a', 'b', 'c'] # sum(strings) # This will raise a TypeError # Correct way to join strings words = ['hello', ' ', 'world'] joined_string = ''.join(words) print(joined_string) # Output: hello world ``` ### Response #### Success Response (200) - **total** (number) - The sum of the items in the iterable plus the start value. #### Response Example ```json { "total": 15 } ``` ``` -------------------------------- ### Install python-twitter Package Source: https://github.com/jython/book/blob/master/GUIApplications.rst Use easy_install to install the python-twitter package and its dependency, simplejson. ```bash jython easy_install python-twitter ``` -------------------------------- ### Run Google App Engine SDK Demo Source: https://github.com/jython/book/blob/master/DeploymentTargets.rst Execute the demo application from the Google App Engine SDK. This command starts the development web server for testing. ```bash /bin/dev_appserver.sh demos/guestbook/war ``` -------------------------------- ### Setup SQLAlchemy Database Engine and Table Source: https://github.com/jython/book/blob/master/DatabasesAndJython.rst Initializes the SQLAlchemy engine with a connection string and defines a 'player' table with columns and a primary key sequence. Requires 'zxoracle' and SQLAlchemy modules. ```python #Import sqlalchemy module and zxoracle >>> import zxoracle >>> from sqlalchemy import create_engine >>> from sqlalchemy import Table, Column, String, Integer, MetaData, ForeignKey >>> from sqlalchemy.schema import Sequence # Create engine >>> db = create_engine('zxoracle://schema:password@hostname:port/database’) ``` ```python # Create metadata and table >>> metadata = MetaData() >>> player = Table('player', metadata, ... Column('id', Integer, Sequence('id_seq'), primary_key=True), ... Column('first', String(50)), ... Column('last', String(50)), ... Column('position', String(30))) ``` ```python >>> metadata.create_all(db) ``` -------------------------------- ### Initialize Jython Twitter GUI Source: https://github.com/jython/book/blob/master/GUIApplications.rst Sets up the main JFrame, login panel with username and password fields, and a login button. The frame is packed and made visible. ```python def __init__(self): self.frame = JFrame("Jython Twitter") self.frame.defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE self.loginPanel = JPanel(GridLayout(0,2)) self.frame.add(self.loginPanel) self.usernameField = JTextField('',15) self.loginPanel.add(JLabel("username:", SwingConstants.RIGHT)) self.loginPanel.add(self.usernameField) self.passwordField = JPasswordField('', 15) self.loginPanel.add(JLabel("password:", SwingConstants.RIGHT)) self.loginPanel.add(self.passwordField) self.loginButton = JButton('Log in',actionPerformed=self.login) self.loginPanel.add(self.loginButton) self.message = JLabel("Please Log in") self.loginPanel.add(self.message) self.frame.pack() self.frame.visible = True ``` -------------------------------- ### Install virtualenv with Jython Source: https://github.com/jython/book/blob/master/appendixA.rst Use easy_install with Jython to install the virtualenv package from the Python Package Index. ```bash jython easy_install.py virtualenv ``` -------------------------------- ### Create and Activate Virtual Environment (Linux) Source: https://github.com/jython/book/blob/master/README.md Create a virtual environment named 'venv', activate it using the source command, and then install project dependencies from requirements.txt. This ensures project isolation. ```bash $ python3 -m virtualenv venv Using base prefix '/usr' ... $ source venv/bin/activate (venv) $ pip install -r book/requirements.txt ``` -------------------------------- ### Start Django App Source: https://github.com/jython/book/blob/master/JythonDjango.rst Create a new Django app within your project. Ensure you are in the project's root directory (e.g., the 'pollsite' directory). ```bash $ jython manage.py startapp polls ``` -------------------------------- ### slice([start,] stop[, step]) Source: https://github.com/jython/book/blob/master/sandbox/builtins.rst Returns a slice object representing the set of indices specified by range(start, stop, step). ```APIDOC ## slice([start,] stop[, step]) ### Description Return a :term:`slice` object representing the set of indices specified by ``range(start, stop, step)``. The *start* and *step* arguments default to ``None``. Slice objects have read-only data attributes :attr:`start`, :attr:`stop` and :attr:`step` which merely return the argument values (or their default). They have no other explicit functionality; however they are used by Numerical Python and other third party extensions. Slice objects are also generated when extended indexing syntax is used. For example: ``a[start:stop:step]`` or ``a[start:stop, i]``. See :func:`itertools.islice` for an alternate version that returns an iterator. ### Method N/A (Built-in function) ### Endpoint N/A (Built-in function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python my_slice = slice(1, 5, 2) print(my_slice.start) # Output: 1 print(my_slice.stop) # Output: 5 print(my_slice.step) # Output: 2 my_list = [0, 1, 2, 3, 4, 5] print(my_list[my_slice]) # Output: [1, 3] ``` ### Response #### Success Response (200) - **start** (int or None) - The starting index of the slice. - **stop** (int or None) - The ending index of the slice. - **step** (int or None) - The step value of the slice. #### Response Example ```json { "start": 1, "stop": 5, "step": 2 } ``` ``` -------------------------------- ### Specifying Package Version with easy_install Source: https://github.com/jython/book/blob/master/appendixA.rst This command demonstrates how to install a specific version of a package using easy_install by appending '==' to the package name. ```bash $ easy_install python-twitter==0.5 ``` -------------------------------- ### Doctest Example: is_even function Source: https://github.com/jython/book/blob/master/TestingIntegration.rst This function includes a docstring with doctest examples to verify its behavior with various integer and float inputs. ```python def is_even(number): """ Checks if an integer number is even. >>> is_even(0) True >>> is_even(2) True >>> is_even(3) False It works with very long numbers: >>> is_even(100000000000000000000000000000) True And also with negatives: >>> is_even(-1000000000000000000000000000001) False But not with floats: >>> is_even(4.1) Traceback (most recent call last): ... ValueError: 4.1 isn't an integer However, a value of type float as long as it value is an integer: >>> is_even(4.0) True """ remainder = number % 2 if 0 < remainder < 1: raise ValueError("%f isn't an integer" % number) return remainder == 0 ``` -------------------------------- ### Jython Greeter with optparse and Decorators Source: https://github.com/jython/book/blob/master/JythonIDE.rst This example demonstrates a more advanced Jython script using optparse for argument parsing and decorators to register different UI handlers. It supports multiple languages and UI outputs (console and window). ```python # -*- coding: utf-8 -*- import sys from optparse import OptionParser greetings = dict(en=u'Hello %s!', es=u'Hola %s!', fr=u'Bonjour %s!', pt=u'Alò %s!') uis = {} def register_ui(ui_name): def decorator(f): uis[ui_name] = f return f return decorator def message(ui, msg): if ui in uis: uis[ui](msg) else: raise ValueError("No greeter named %s" % ui) def list_uis(): return uis.keys() @register_ui('console') def print_message(msg): print msg @register_ui('window') def show_message_as_window(msg): from javax.swing import JFrame, JLabel frame = JFrame(msg, defaultCloseOperation=JFrame.EXIT_ON_CLOSE, size=(100, 100), visible=True) frame.contentPane.add(JLabel(msg)) if __name__ == "__main__": 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(sys.argv) if len(args) < 2: print "Sorry, I can't greet you if you don't say your name" sys.exit(1) if options.lang not in greetings: print "Sorry, I don't speak '%s'" % options.lang sys.exit(1) msg = greetings[options.lang] % args[1] try: message(options.ui, msg) except ValueError, e: print "Invalid UI name\n" print "Valid UIs:\n\n" + "\n".join(' * ' + ui for ui in list_uis()) ssys.exit(1) ``` -------------------------------- ### Pylons Interactive Shell Example Source: https://github.com/jython/book/blob/master/IntroToPylons.rst Demonstrates basic interaction with a Pylons application in its interactive shell, including making requests and inspecting responses. ```python >>> resp = app.get('/roster/index') >>> resp >>> resp.req ``` -------------------------------- ### zxJDBC Connection Establishment and Closing Source: https://github.com/jython/book/blob/master/DatabasesAndJython.rst Examples of establishing and closing zxJDBC connections, demonstrating the use of the 'with' statement (for Jython 2.5.1+) and the try-finally block for older versions. ```APIDOC ## Establishing and Closing zxJDBC Connections ### Description This section provides examples for connecting to a database using zxJDBC and ensuring the connection is properly closed. It highlights the difference between using the `with` statement (available in Jython 2.5.1 and later) and the traditional `try...finally` block for managing connection lifecycles. ### Method `zxJDBC.connect()` ### Endpoint N/A (This is a library function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example (using `with` statement) ```python from __future__ import with_statement from com.ziclix.python.sql import zxJDBC jdbc_url = "jdbc:postgresql:test" username = "postgres" password = "jython25" driver = "org.postgresql.Driver" with zxJDBC.connect(jdbc_url, username, password, driver) as conn: do_something(conn) # Connection is automatically closed here ``` ### Request Example (using `try...finally` for older Jython versions) ```python from com.ziclix.python.sql import zxJDBC jdbc_url = "jdbc:postgresql:test" username = "postgres" password = "jython25" driver = "org.postgresql.Driver" try: conn = zxJDBC.connect(jdbc_url, username, password, driver) do_something(conn) finally: conn.close() ``` ### Response #### Success Response (200) N/A (This is a function call, not an HTTP endpoint) #### Response Example N/A ``` -------------------------------- ### Create a Jython Servlet Source: https://context7.com/jython/book/llms.txt Implement a Jython servlet by extending HttpServlet. This example defines doGet and doPost methods to handle HTTP requests and generate HTML responses. ```python # NewJythonServlet.py from javax.servlet.http import HttpServlet class NewJythonServlet(HttpServlet): def doGet(self, request, response): self.doPost(request, response) def doPost(self, request, response): toClient = response.getWriter() response.setContentType("text/html") toClient.println("Jython Servlet Test" + "

Servlet Jython Servlet at " + request.getContextPath() + "

") def getServletInfo(self): return "Short Description" ``` -------------------------------- ### Install virtualenv (Linux) Source: https://github.com/jython/book/blob/master/README.md Install the virtualenv package on Linux systems using pip. This tool is necessary for creating isolated Python environments. ```bash $ python3 -m pip install virtualenv ... ``` -------------------------------- ### Install yolk utility with Jython Source: https://github.com/jython/book/blob/master/appendixA.rst Install the 'yolk' utility using ez_install.py with Jython. Ensure you are using Jython 2.5.1 or later and JDK 1.6 or above. ```bash jython ez_install.py yolk ``` -------------------------------- ### Initialize Django Database Source: https://github.com/jython/book/blob/master/JythonDjango.rst Run the 'manage.py syncdb' command to initialize the Django database, creating necessary tables and prompting for superuser creation. ```shell > 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 ``` -------------------------------- ### Create and Start a Daemon Thread Source: https://github.com/jython/book/blob/master/Concurrency.rst Set a thread to be a daemon thread before starting it. Daemon threads are terminated upon JVM shutdown without cleanup. ```python # create a thread t t.setDaemon(True) t.start() ``` -------------------------------- ### Jythonc Compiler Output Example Source: https://github.com/jython/book/blob/master/appendixB.rst This is an example of the output seen when the jythonc compiler successfully processes a Jython class intended for use as an Ant task. ```text processing SimpleTask Required packages: ``` -------------------------------- ### Inspecting Request GET Parameters Source: https://github.com/jython/book/blob/master/IntroToPylons.rst Shows how to access and interpret GET parameters from a request, including handling multiple values for the same parameter using UnicodeMultiDict. ```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'] ``` -------------------------------- ### Using Jython in an IDE (Netbeans) Source: https://github.com/jython/book/blob/master/toc.txt Explains how to set up and develop Jython applications within the Netbeans IDE, covering environment configuration and project development steps. ```text # Setup involves installing the Jython plugin for Netbeans and configuring the interpreter. ``` -------------------------------- ### Generate SQL for App Models Source: https://github.com/jython/book/blob/master/JythonDjango.rst Use the `sqlall` management command with an app label to print the SQL statements for creating tables for that app's models. ```bash $ jython manage.py sqlall polls ``` -------------------------------- ### Initializing a Coroutine Source: https://github.com/jython/book/blob/master/DefiningFunctionsandUsingBuilt-Ins.rst Demonstrates how to initialize a coroutine by calling next() on its instance. This prepares the coroutine to accept values. ```python ex = co_example("example1") ex.next() ``` -------------------------------- ### Install virtualenv (Windows PowerShell) Source: https://github.com/jython/book/blob/master/README.md Install the virtualenv package if it's not already present on your system using pip. This is a prerequisite for creating isolated Python environments. ```powershell PS dg-jython> python3 -m pip install virtualenv ``` -------------------------------- ### Running Hudson Locally Source: https://github.com/jython/book/blob/master/TestingIntegration.rst Execute the Hudson WAR file to start a local instance. Access it via http://localhost:8080/. Be aware of security implications regarding user privileges. ```bash java -jar hudson.war ``` -------------------------------- ### Basic Unittest TestCase for Math Functions Source: https://github.com/jython/book/blob/master/TestingIntegration.rst A simple example demonstrating how to create a test case by subclassing unittest.TestCase and defining test methods for math functions. ```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)) ``` -------------------------------- ### Creating and Accessing a List Source: https://github.com/jython/book/blob/master/LangSyntax.rst Demonstrates how to create a list of numbers and access elements using zero-based indexing. ```Python >>> my_numbers = [1, 2, 3, 4, 5] >>> my_numbers [1, 2, 3, 4, 5] >>> my_numbers[1] 2 ``` -------------------------------- ### List installed packages with yolk Source: https://github.com/jython/book/blob/master/appendixA.rst Use the 'yolk -l' command to list all installed packages within the current Jython environment, including their versions and status (active/non-active development). ```bash yolk -l Django - 1.0.2-final - non-active development (/jython2.5.1/Lib/site-packages) Django - 1.0.3 - active development (/jython2.5.1/Lib/site-packages/Django-1.0.3-py2.5.egg) Django - 1.1 - non-active development (/jython2.5.1/Lib/site-packages) SQLAlchemy - 0.5.4p2 - active development (/jython2.5.1/Lib/site-packages) SQLAlchemy - 0.6beta1 - non-active development (/jython2.5.1/Lib/site-packages) ``` -------------------------------- ### Get Unicode character from code point Source: https://github.com/jython/book/blob/master/sandbox/builtins.rst Use unichr() to get a Unicode string of one character from its integer Unicode code point. This is the inverse of ord() for Unicode strings. ```python unichr(97) ``` -------------------------------- ### Define and Use Classes in Jython Source: https://context7.com/jython/book/llms.txt Illustrates defining a class with an initializer, methods, and class constants. Demonstrates object instantiation and method calls. ```python class Car(object): NORTH = 0 EAST = 1 SOUTH = 2 WEST = 3 def __init__(self, x=0, y=0): self.x = x self.y = y self.direction = 0 def turn_right(self): self.direction += 1 self.direction = self.direction % 4 def turn_left(self): self.direction -= 1 self.direction = self.direction % 4 def move(self, distance): if self.direction == self.NORTH: self.y += distance elif self.direction == self.SOUTH: self.y -= distance elif self.direction == self.EAST: self.x += distance else: self.x -= distance def position(self): return (self.x, self.y) # Usage c = Car() c.turn_right() c.move(5) print c.position() # (5, 0) ``` -------------------------------- ### Accessing List Elements by Index Source: https://github.com/jython/book/blob/master/DataTypes.rst Use positive indexes to access elements from the beginning of the list (starting at 0) and negative indexes to access elements from the end of the list (starting at -1). ```python >>> my_string_list[0] 'Hello' >>> my_string_list[2] 'Lists' ``` ```python >>> my_string_list[-1] 'Lists' >>> my_string_list[-2] 'Jython' ``` -------------------------------- ### Create a Jython virtual environment Source: https://github.com/jython/book/blob/master/appendixA.rst Create a new virtual environment named JY2.5.1Env using the virtualenv.py module. This will create a Jython executable and install setuptools within the new environment. ```bash jython <>/jython2.5.1/Lib/site-packages/virtualenv-1.3.3-py2.5.egg/virtualenv.py JY2.5.1Env New jython executable in JY2.5.1Env/bin/jython Installing setuptools............done. ``` -------------------------------- ### Example Nose Test Failure Output Source: https://github.com/jython/book/blob/master/TestingIntegration.rst This is an example of the output when unit tests fail. It shows specific errors, including AttributeError, indicating missing functions or attributes in the tested module. ```text EEEEEEE ====================================================================== ERROR: testIsSolution (eightqueens.test_checker.SolutionTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/path/to/eightqueens/test_checker.py", line 149, in testIsSolution self.assert_(checker.is_solution(BOARD_WITH_SOLUTION)) AttributeError: 'module' object has no attribute 'is_solution' ====================================================================== ERROR: testColsOK (eightqueens.test_checker.PartialSolutionTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/path/to/eightqueens/test_checker.py", line 100, in testColsOK self.assert_(checker._cols_ok(BOARD_WITH_SOLUTION)) AttributeError: 'module' object has no attribute '_cols_ok' ====================================================================== ERROR: testDiagonalsOK (eightqueens.test_checker.PartialSolutionTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/path/to/eightqueens/test_checker.py", line 104, in testDiagonalsOK self.assert_(checker._diagonals_ok(BOARD_WITH_SOLUTION)) AttributeError: 'module' object has no attribute '_diagonals_ok' ====================================================================== ERROR: testRowsOK (eightqueens.test_checker.PartialSolutionTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/path/to/eightqueens/test_checker.py", line 96, in testRowsOK self.assert_(checker._rows_ok(BOARD_WITH_SOLUTION)) AttributeError: 'module' object has no attribute '_rows_ok' ====================================================================== ERROR: testValidateContents (eightqueens.test_checker.ValidationTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/path/to/eightqueens/test_checker.py", line 81, in testValidateContents self.assertFalse(checker._validate_contents(BOARD_FULL_OF_CRAP)) AttributeError: 'module' object has no attribute '_validate_contents' ``` -------------------------------- ### Connect to a Database Source: https://github.com/jython/book/blob/master/sandbox/database.rst Establishes a connection to a database using JDBC URL, username, password, and driver. Ensure the JDBC driver is available in the classpath. ```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 ``` -------------------------------- ### Execute Python Code using JSR-223 ScriptEngine Source: https://github.com/jython/book/blob/master/JythonAndJavaIntegration.rst Use the JSR-223 API to get a Python script engine and execute Python code. This method allows setting and getting variables between Java and Python. ```Java import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class Main { public static void main(String[] args) throws ScriptException { ScriptEngine engine = new ScriptEngineManager().getEngineByName("python"); engine.eval("import sys"); engine.eval("print sys"); engine.put("a", 42); engine.eval("print a"); engine.eval("x = 2 + 2"); Object x = engine.get("x"); System.out.println("x: " + x); } } ``` -------------------------------- ### Define and Use Functions in Jython Source: https://context7.com/jython/book/llms.txt Shows how to define simple functions, functions with parameters and return values, and how functions can be treated as first-class objects. ```python # Simple function definition def my_simple_function(): print 'This is a really basic function' my_simple_function() # Function with parameters def multiply_nums(x, y): return x * y result = multiply_nums(25, 7) # Returns 175 # Functions as first-class objects def perform_math(oper): return oper(5, 6) perform_math(multiply_nums) # Returns 30 ``` -------------------------------- ### Invoking the built-in help system with help() Source: https://github.com/jython/book/blob/master/appendixC.rst Starts the interactive help system or displays help for a specific object or topic. This function is primarily intended for interactive use and is added by the site module. ```python help([object]) ```