Welcome to TiddlyWiki created by Jeremy Ruston, Copyright © 2007 UnaMesa Association
KS link http://www.irb.hr/users/maks/ui.html
Klikni na menu [[Korisnička sučelja]], [[Python]] ...
!! knjige
[[wxPython in Action (pdf) |wxact.pdf]]
[[Online knjiga Think_Python (html) |http://en.wikibooks.org/wiki/Think_Python]]
[[Online TCUID (html)| http://hcibib.org/tcuid/]]
[[Vjezba]]
http://www.irb.hr/users/maks/vjezbe8/
Prazni tiddly html file (desni klik i "Save Link As") [[empty|empty.html]]
[[Demystifying Usability : How Usable is Jakob Nielsen?|http://experiencedynamics.blogs.com/site_search_usability/2004/04/how_usable_is_j.html]]
2) Professional ethics. A few years ago (circa 2000), Nielsen posted on his home page that his fees were roughly $35,000 for a half day high level strategy consulting session. This is where the credibility started to erode for me. If anybody thought usability was expensive, Nielsen certainly contributed to that perception (despite his current claims that usability is cheap: "Usability for $200" and "ROI for Usability").
Source: [[Demystifying Usability : How Usable is Jakob Nielsen?|http://experiencedynamics.blogs.com/site_search_usability/2004/04/how_usable_is_j.html]]
[[Iterative Design of User Interfaces (Jakob Nielsen)|http://www.useit.com/papers/iterative_design/]]
[[Java Look and Feel Design Guidelines|http://java.sun.com/products/jlf/ed2/book/index.html]]
Contents
Foreword by James Gosling
Preface
Part I: Overview
1: The Java Look and Feel
Fundamentals of the Java Look and Feel
Visual Tour of the Java Look and Feel
~MetalEdit Application
Retirement Savings Calculator Applet
2: The Java Foundation Classes
Java 2 Software Development Kit
Java Foundation Classes
Support for Accessibility
Support for Internationalization
User Interface Components of the JFC
Pluggable Look and Feel Architecture
Example Model and Interfaces
Client Properties
Major JFC User Interface Components
Look and Feel Options
Java Look and Feel the Recommended Design
Supplied Designs
Part II: Fundamental Java Application Design
3: Design Considerations
Choosing an Application or an Applet
Distribution
Security Issues
Placement of Applets
Designing for Accessibility
Benefits of Accessibility
Accessible Design
Planning for Internationalization and Localization
Benefits of Global Planning
Global Design
4: Visual Design
Themes
Colors
Fonts
Layout and Visual Alignment
Design Grids
Text Layout
~Between-Component Spacing Guidelines
Spacing Guidelines for Specific JFC Components
Text in the Interface
Headline Capitalization in English
Sentence Capitalization in English
Animation
5: Application Graphics
Working With ~Cross-Platform Color
Working With Available Colors
Choosing Graphic File Formats
Choosing Colors
Maximizing Color Quality
Categorizing Application Graphics
Designing Icons
Working With Icon Styles
Drawing Icons
Designing Button Graphics
Using Button Graphic Styles
Producing the Flush 3D Effect
Working With Button Borders
Determining the Primary Drawing Area
Drawing the Button Graphic
Using Badges in Button Graphics
Menu Indicators
New Object Indicators
Add Object Indicators
Properties Indicators
Combining Indicators
Designing Symbols
Designing Graphics for Corporate and Product Identity
Designing Splash Screens
Designing Login Splash Screens
Designing About Boxes
6: Behavior
Mouse Operations
Pointer Feedback
Mouse-over Feedback
Clicking and Selecting Objects
Displaying Contextual Menus
~Drag-and-Drop Operations
Typical Drag and Drop
Pointer and Destination Feedback
Keyboard Operations
Keyboard Focus
Keyboard Navigation and Activation
Keyboard Shortcuts
Mnemonics
Operational Feedback
Progress Animation
Status Animation
Design for Smooth Interaction
Initial Focus
Navigation
Password Field
Status and Error Messages
Text Selection and Filled Text Fields
Part III: The Components of the Java Foundation Classes
7: Windows and Panes
Anatomy of a Primary Window
Constructing Windows
Primary Windows
Secondary Windows
Plain Windows
Utility Windows
Organizing the Contents of Windows
Panels
Scroll Panes
Tabbed Panes
Split Panes
Working With Multiple Document Interfaces
Backing Windows
Internal Windows
Secondary Windows
Internal Utility Windows
Window Titles
Title Text in Primary Windows
Title Text in Secondary Windows
Title Text in Internal Windows
8: Dialog Boxes and Alert Boxes
Modal and Modeless Dialog Boxes
Dialog Box Design
Tab Traversal Order
~Single-Use and ~Multiple-Use Dialog Boxes
Command Buttons in Dialog Boxes
Common Dialog Boxes
Find Dialog Boxes
Login Dialog Boxes
Preferences Dialog Boxes
Progress Dialog Boxes
Color Choosers
Alert Boxes
Info Alert Boxes
Warning Alert Boxes
Error Alert Boxes
Question Alert Boxes
9: Menus and Toolbars
Menu Elements
Menu Bars
Drop-down Menus
Submenus
Menu Items
Separators
Menu Item Graphics
Checkbox Menu Items
Radio Button Menu Items
Common Menus
Typical File Menu
Typical Edit Menu
Typical Format Menu
Typical View Menu
Typical Help Menu
Contextual Menus
Toolbars
Toolbar Placement
Draggable Toolbars
Toolbar Buttons
Tool Tips
10: Basic Controls
Command Buttons
Default Command Buttons
Combining Graphics With Text in Command Buttons
Using Ellipses in Command Buttons
Toggle Buttons
Independent Choice
Exclusive Choice
Checkboxes
Radio Buttons
List Boxes
Scrolling
Selection Models for List Components
Combo Boxes
Noneditable Combo Boxes
Editable Combo Boxes
Sliders
11: Text Components
Labels
Labels That Identify Controls
Labels That Communicate Status and Other Information
Text Fields
Noneditable Text Fields
Editable Text Fields
Password Fields
Text Areas
Editor Panes
Default Editor Kit
Styled Text Editor Kit
RTF Editor Kit
HTML Editor Kit
12: Selectable Lists, Tables, and Tree Components
Selectable Lists
Selectable Lists and Associated Tables
Selectable Lists and Associated Text Fields
Tables
Table Appearance
Table Scrolling
Column Reordering
Column Resizing
Row Sorting
Selection Models for Tables
Tree Components
Lines in Tree Components
Graphics in Tree Components
Editing in Tree Components
Part IV: Backmatter
Appendix A: Keyboard Shortcuts, Mnemonics, and Other Keyboard
Operations
Common Keyboard Shortcuts
Common Mnemonics
Backing Windows and Internal Windows
Checkboxes
Combo Boxes
Command Buttons
HTML Editor Kits
List Components
Menus
Radio Buttons
Scrollbars
Secondary Windows and Utility Windows
Sliders
Split Panes
Tabbed Panes
Tables
Text Areas and Default and Styled Text Editor Kits
Text Fields
Toggle Buttons
Tool Tips
Toolbars
Tree Components
Appendix B: Graphics Repository
General Graphics
Adding Objects
Saving Edits or Checkpoints
Stopping a Task
Updating the Screen Display
Changing Magnification Levels
Specifying Preferences and Properties
Printing
Displaying and Retrieving Previously Visited Locations
Creating and Sending Electronic Mail
Aligning Objects
Justifying Objects
Searching
Editing Objects and Data
Importing and Exporting Objects
Providing Help and Information
Navigation
Vertical Traversal
Horizontal Traversal
Returning to an Initial Location
Table Graphics
Column Operations
Row Operations
Text
Text Alignment and Justification
Type Style Graphics
Media
Creating a Movie
Moving Through ~Time-Based Media
Graphics for Development Tools
Creating and Deploying Applications and Applets
Creating and Adding Beans and Enterprise Beans
Creating Hosts and Servers
Creating and Adding Java Archive Files
Creating and Adding Web Archive Files and Web Components
Appendix C: Localization Word Lists
European Languages
Asian Languages
Appendix D: Switching Look and Feel Designs
Pitfalls of ~User-Controlled Switching
Guidelines for Switching Look and Feel Designs
How to Present the Choice
Nomenclature
Index
Java Look and Feel Design Guidelines, second edition.
Copyright 2001. Sun Microsystems, Inc. All Rights Reserved
Source: [[Java Look and Feel Design Guidelines|http://java.sun.com/products/jlf/ed2/book/index.html]]
!! Wiki
<<tagging wiki>>
!! Web
<<tagging html>>
''''
[[Korisnička sučelja]]
--------------------------
[[Python]]
[[tiddlygrimoire|tiddlygrimoire.html]]
-----------------------
{{small{
<<search>>
<<closeAll>>
<<permaview>>
<<newTiddler>>
<<saveChanges>>
}}}
---------------------------
{{smaller{ Site created and maintained by
A. [[M.|http://www.irb.hr/users/maks/ui.html]]
}}}
PARC
Founded 1970
Headquarters Palo Alto, California, USA
Industry R&D
Website www.parc.com
PARC entrance.
Xerox PARC old logo.
PARC (Palo Alto Research Center, Inc.), formerly Xerox PARC, is a research and development company in Palo Alto, California with a distinguished reputation for its contributions to information technology.
Founded in 1970 as a division of Xerox Corporation, PARC has been responsible for such well known and important developments as ''laser printing, the Ethernet, the modern personal computer graphical user interface (GUI), ubiquitous computing, and advancing very-large-scale-integration (VLSI)''.
Incorporated as a wholly owned subsidiary of Xerox in 2002, PARC currently conducts research into biomedical technologies, "clean technology", user interface design, sensemaking, ubiquitous computing, large area electronics, and embedded and intelligent systems.
Source: [[PARC (company) - Wikipedia, the free encyclopedia|http://en.wikipedia.org/wiki/Xerox_Palo_Alto_Research_Center]]
<!--{{{-->
<div class='header' macro='gradient vert [[ColorPalette::PrimaryLight]] [[ColorPalette::PrimaryMid]]'>
<div class='headerShadow'>
<span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>
<span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>
</div>
<div class='headerForeground'>
<span class='siteTitle' refresh='content' tiddler='SiteTitle'></span>
<span class='siteSubtitle' refresh='content' tiddler='SiteSubtitle'></span>
</div>
</div>
<div id='mainMenu' refresh='content' tiddler='MainMenu'></div>
<div id='sidebar'>
<div id='sidebarOptions' refresh='content' tiddler='SideBarOptions'></div>
<div id='sidebarTabs' refresh='content' force='true' tiddler='SideBarTabs'></div>
</div>
<div id='displayArea'>
<div id='messageArea'></div>
<div id='tiddlerDisplay'></div>
</div>
<!--}}}-->
!wx apps
Aplikacija poput gtk-demo python samo za wx.
U ''tree'' kontroli su imena aplikacija (ili dijelova programa, funkcija, klasa itd..). Odabirom imena aplikacije u tree kontroli s desne strane se ispisuje u ''notebook'' kontroli opis aplikacije odnosno kod aplikacije u drugom prozoru notebook kontrole. To je jako pojednostavljena ideja koju vidimo u wxDemo programu. Aplikacija iz opisa programa, napravi kratki opis (u tree kontroli) i detaljni opis u notebooku. Ne želimo voditi evideniciju o programima, već ih samo treba staviti u isti direktorij s aplikacijom.
Fali:
* Ime programa
* Da li treba Save funkcija? Ili je Copy/Paste dovoljan?
* Fiksni direktorij, zapisan u programu?
[img[wxApps.png]]
!! Implementacija
!!! Izbornik i Opis
Koristimo isti princip kao u pygtk-demo. Prva linija u doc stringu za pojedini model se nalazi u listi, dok je opis kompletan doc string
{{{
import os
demopath=os.curdir
_file_list = [
x for x in os.listdir(demopath)
if len(x) > 3 and x[-3:] == '.py']
demo_list = []
for _mod in _file_list:
try:
doc1=''
#print _mod
modul=_mod[:-3]
exec('from '+ modul+ ' import __doc__ as doc1')
_description = doc1.splitlines()[0]
demo_list.append((_description, _mod,doc1))
except (ImportError, AttributeError), msg:
pass
demo_list.sort()
}}}
Pročitaju se svi fileovi u trenutnom direktoriju, demo_list sadrži kratak opis kao prvi član, zatim ime file-a kao drugi član i kompletan opis kao treći član.
!!UI
Umjesto tree kontrole izabrana je lista, tako da ne možemo imati grananje što je dovoljno za mali broj modula. Koristili smo wxglade za prvu konstrukciju ~UI-a. Opis modula prikazan je u wx.html prozoru, a program koristi stc, tj. ~StyledTextCtrl. Korisitimo
{{{
import wx
import wx.html
import keyword
import wx.stc as stc
from listpys import demo_list
}}}
Funkcije
{{{
self.__set_properties()
self.__do_layout()
}}}
definiraju oblik, položaj i veličine prozora.
U glavnom prozoru koristimo Notebook s dva prozora (opis i code), a s lijeve strane je ~ListBox
{{{
lass MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: MyFrame.__init__
kwds["style"] = wx.CAPTION|wx.CLOSE_BOX|wx.MINIMIZE_BOX|wx.MAXIMIZE_BOX|wx.STAY_ON_TOP|wx.SYSTEM_MENU|wx.RESIZE_BORDER|wx.CLIP_CHILDREN
wx.Frame.__init__(self, *args, **kwds)
self.notebook_1 = wx.Notebook(self, -1, style=0)
self.lb = wx.ListBox(self, -1)
self.__set_properties()
self.noteinfo = wx.Panel(self.notebook_1, -1)
self.notebook_1_pane_2 = wx.Panel(self.notebook_1, -1)
self.info = wx.html.HtmlWindow(self.notebook_1)
self.code= stc.StyledTextCtrl(self.notebook_1_pane_2,-1,style=wx.EXPAND)
.........................................................
}}}
Trenutni izgled aplikacije
[img[wxApp1.png]]
! Image viewer,pdf ili mp3 kolekcije
* Fiksni direktorij ili s komandne linije. Konfiguracija?
* Da li funkcija pronalazi sve datoteke?
* Grafički izgled i funkcije?
! poker kocki
* Provjeriti funkcije bez GUI programa
*Grafički izgled i funkcije?
* Posebni gumbi za pokretanje zaustavljanje bacanja kocki?
* Slike za kocke?
Knjige i linkovi:
*http://effbot.org/
** http://effbot.org/zone/librarybook-index.htm
** http://effbot.org/tkinterbook/
*http://openbookproject.net//py4fun/index.html
!wxpython
*http://wxpython.org/
*http://wxpython.org/onlinedocs.php
*http://wiki.wxpython.org/FrontPage
*http://wiki.wxpython.org/RecipesControls
*http://wiki.wxpython.org/Using%20wxPython%20Demo%20Code
*http://wiki.wxpython.org/UsingSizers
*http://wiki.wxpython.org/wxDesigner%20Sizer%20Tutorial
*http://www.wxpython.org/docs/api/wx.Sizer-class.html
*http://www.linuxquestions.org/questions/programming-9/wxpython-sizers-panels-frames-confusion-696723/
*http://zetcode.com/wxpython/
!! UNIX
[[shell]]
<hr>
<<tagging python>>
<<search>><<closeAll>><<permaview>><<newTiddler>><<newJournal "DD MMM YYYY" "journal">><<saveChanges>><<slider chkSliderOptionsPanel OptionsPanel "options »" "Change TiddlyWiki advanced options">>
[[Slashdot : Jakob Nielsen Answers Usability Questions|http://developers.slashdot.org/article.pl?sid=00/03/03/096223&mode=thread]]
/* Modied Style from Julian Knight JK Version: 2006-04-20 (Simplified) */
body {position:static;}
.tagClear {margin-top:1em;clear:both;}
hr {height:0px;border:0;border-top:1px solid silver;}
h1,h2,h3,h4,h5 {color:#014;background:transparent;border-bottom:1px solid #ddd;padding-left:0;}
.headerShadow {padding:.5em 0em .5em 1em;}
.headerForeground {padding:.5em 0em .5em 1em;}
#displayArea { /* The bit that contains all tiddlers */
padding-top:.1em;padding-bottom:.1em;
margin-top:0;margin-right:15.5em;margin-bottom:0;margin-left:12.5em;-moz-border-radius:1em;}
.tiddler {-moz-border-radius:1em;border-top:1px solid #ccc;border-left:1px solid #ccc;
border-bottom:3px solid #ccc;border-right:3px solid #ccc;margin:0.5em;background:#fff;padding:0.5em;}
.subtitle { /* Tiddler subtitle */
font-size:0.9em;text-align:right;}
.viewer pre {padding: 0;margin-left: 0;}
.viewer hr {border: solid 1px silver;}
.toolbar {visibility:visible;}
.selected .toolbar {visibility:visible;color:#00f;}
.tagging, .tagged, .selected .tagging, .selected .tagged {
font-size:75%; padding:0.3em; background-color:#eee;border-top:1px solid #ccc; border-left:1px solid #ccc;
border-bottom:3px solid #ccc; border-right:3px solid #ccc;max-width:45%;-moz-border-radius:1em;}
.noBorder,.noBorder td,.noBorder th,.noBorder tr{border:0 !important}
.evenRow{} .oddRow{}
.headerShadow { visibility: hidden; }
.toolbar .button { color:#dee; }
.selected .toolbar .button { color:#014;}
/* Uncoment next two lines to hide sidebar */
#sidebar{display:none;}
#displayArea {margin: 1em 1em 0em 14em;}
.smaller { font-size:80%; }
.small { font-size:90%; }
#contentWrapper .wrappingClass img {width: 100%}
#contentWrapper .wrappingClass2 img {width: 50%}
/***
!Colors Used
*@@bgcolor(#8cf): #8cf - Background blue@@
*@@bgcolor(#18f): #18f - Top blue@@
*@@bgcolor(#04b): #04b - Mid blue@@
*@@bgcolor(#014):color(#fff): #014 - Bottom blue@@
*@@bgcolor(#ffc): #ffc - Bright yellow@@
*@@bgcolor(#fe8): #fe8 - Highlight yellow@@
*@@bgcolor(#db4): #db4 - Background yellow@@
*@@bgcolor(#841): #841 - Border yellow@@
*@@bgcolor(#703):color(#fff): #703 - Title red@@
*@@bgcolor(#866): #866 - Subtitle grey@@
!Generic Rules
/***
!Message Area /%=================================================%/
***/
/*{{{*/
#messageArea {
border: 1px solid #841;
background: #db4;
color: #014;
}
#messageArea .button {
padding: 0.2em 0.2em 0.2em 0.2em;
color: #014;
background: #fff;
}
/*}}}*/
neki jhs jhsakjhsa
[[aa]]
[[Top-10 Application-Design Mistakes (Jakob Nielsen's Alertbox)|http://www.useit.com/alertbox/application-mistakes.html]]
The design of a user interface affects the __amount of effort the user must expend to provide input __ for the system and to __interpret the output__ of the system, and how much effort it takes to __learn how to do this__. Usability is the degree to which the design of a particular user interface takes into account the human psychology and physiology of the users, and makes the process of using the system effective, efficient and satisfying.
*Usability is mainly a characteristic of the user interface, but is also associated with the functionalities of the product and the process to design it. It describes how well a product can be used for its intended purpose by its target users with efficiency, effectiveness, and satisfaction, also taking into account the requirements from its context of use.
Source: [[User interface - Wikipedia, the free encyclopedia|http://en.wikipedia.org/wiki/User_interface]]
UI = HCI = MMI
The user interface (also known as Human Computer Interface or ~Man-Machine Interface (MMI)) is the aggregate of means by which people—the users—interact with the system—a particular machine, device, computer program or other complex tool. The user interface provides means of:
* Input, allowing the users to manipulate a system
* Output, allowing the system to indicate the effects of the users' manipulation.
The term user interface is often used in the context of computer systems and electronic devices. The user interface of a mechanical system, a vehicle or an industrial installation is sometimes referred to as the ~Human-Machine Interface (HMI). HMI is a modification of the original term MMI (~Man-Machine Interface). In practice, the abbreviation MMI is still frequently used although some may claim that MMI stands for something different now. Another abbreviation is HCI, but is more commonly used for Human-computer interaction than Human-computer interface. Other terms used are Operator Interface Console (OIC) and Operator Interface Terminal (OIT).
User interfaces in computing
In computer science and human-computer interaction, the user interface (of a computer program) refers to the graphical, textual and auditory information the program presents to the user, and the control sequences (such as keystrokes with the computer keyboard, movements of the computer mouse, and selections with the touchscreen) the user employs to control the program.
[edit] Types
Currently (as of 2009[update]) the following types of user interface are the most common:
* Graphical user interfaces (GUI) accept input via devices such as computer keyboard and mouse and provide articulated graphical output on the computer monitor. There are at least two different principles widely used in GUI design: Object-oriented user interfaces (~OOUIs) and application oriented interfaces[verification needed].
* Web-based user interfaces or web user interfaces (WUI) accept input and provide output by generating web pages which are transmitted via the Internet and viewed by the user using a web browser program. Newer implementations utilize Java, AJAX, Adobe Flex, Microsoft .NET, or similar technologies to provide real-time control in a separate program, eliminating the need to refresh a traditional HTML based web browser. Administrative web interfaces for web-servers, servers and networked computers are often called Control panels.
Source: [[User interface - Wikipedia, the free encyclopedia|http://en.wikipedia.org/wiki/User_interface]]
<div>
<span class='title' style='float:left;' macro='view title'></span>
<span style='float:right;' class='subtitle'>
<span macro='view modifier link'></span>,
<span macro='view modified date DD MMM YYYY'></span>
(created <span macro='view created date DD MMM YYYY'></span>)
</span>
<span class='toolbar' style='clear:right;margin-top:1px;float:right;'
macro='toolbar -closeTiddler +editTiddler deleteTiddler closeOthers permalink references jump'>
</span>
<div class='tagClear'></div>
</div>
<hr>
<div class='tagClear viewer' macro='view text wikified'></div>
Napraviti zadatak na str. 74-77 skripte. Ponovo napraviti imenik u wxpythonu, vidi file phbk1.py.
Ako se ne vidi ~ListBox dodajte size opciju, npr. size=(225,100).
Napraviti aplikaciju tel. imenik (iz prosle vjezbe) pomocu sizer-a.
1. Promjeni convertTemp.py tako da opiše šta radi.
2. Modificiraj Average.py da računa s tri ocjene.
3. Modificiraj convertTemp.py da promjeni stupnjeve C od 0 do 100 u F za svakih 10 stupnjeva.
4. Modificiraj Average.py da računa srednju vrijednost od n brojeva, npr n=5.
5. Napiši program koji pretvara F u C
6. Napiši program koji pretvara K u C, i C u K, ovisno o korisniku'
zoo = ["monkey", "tiger", "eagle"] # define a list
zoo[0] # a single element
zoo[0] = "gorilla" # change an element
zoo.append("parrot") # add elements at end of list
zoo = ["zebra","lion"] + zoo # add elements at beginning
{{{
#!/usr/bin/env python
# creating and modifying a list
#
zoo = ["monkey", "tiger", "eagle", "parrot"]
print "The zoo has the following", len(zoo), "animals:", zoo
print "The 1. animal is", zoo[0]
print "The 2. animal is", zoo[1]
print "The 1. and 2. animals are", zoo[:2]
print "Animals 2. - 4. are", zoo[1:4]
print "The animals after the 2. one are", zoo[2:]
print "The last element is", zoo[-1]
new_animal = raw_input("Which animal would you like to add? ")
zoo.append(new_animal)
print "The zoo has the following", len(zoo), "animals:", zoo
new_animal = raw_input("Which animal should replace the monkey? ")
zoo[0] = new_animal
print "The zoo has the following", len(zoo), "animals:", zoo
}}}
!!! zadatak 1
Napravi listu od 5 imena (kao u primjeru). Isprintaj.
* Dodaj jedno ime.
* Trazi od korisnika da upiše jedno ime i dodaj ga u listu. Isprintaj.
* Isprintaj duljinu liste.
<hr>
{{{
import random
print random.randint(1,5)
for n in range(10):
print n
}}}
print random cijeli broj unutar intervala [1,5]. {{{for}}} petlja printa brojeve od 0 do 9.
!!! zadatak 2
Napravi listu od 10 cijelih brojeva s random generatorom randint, vrijednosti cijelih brojeva u listi moraju biti 0 ili 1.
Napravi histogram, tj. prebroji koliko ima 0, odnosno jedinica i isprintaj rezultat. Sortiraj listu, prvo 0 onda 1.
<hr>
{{{
strs = ['aa', 'BB', 'zz', 'CC']
print sorted(strs) ## ['BB', 'CC', 'aa', 'zz'] (case sensitive)
print sorted(strs, reverse=True) ## ['zz', 'aa', 'CC', 'BB']
strs = ['ccc', 'aaaa', 'd', 'bb']
print sorted(strs, key=len) ## ['d', 'bb', 'ccc', 'aaaa']#
# "key" argument specifying str.lower function to use for sorting
print sorted(strs, key=str.lower) ## ['aa', 'BB', 'CC', 'zz']
}}}
Funkcija pythona sortira listu, u drugom redu koristi argument za redosljed sortiranja. Slijedeći red koristi argument {{{key}}} i sortira prema duljini riječi. I na kraju funkcija {{{str.lower}}} tretira isto mala i velika slova.
{{{
## Say we have a list of strings we want to sort by the last letter of the string.
strs = ['xc', 'zb', 'yd' ,'wa']
## Write a little function that takes a string, and returns its last letter.
## This will be the key function (takes in 1 value, returns 1 value).
def MyFn(s):
return s[-1]
## Now pass key=MyFn to sorted() to sort by the last letter:
print sorted(strs, key=MyFn) ## ['wa', 'zb', 'xc', 'yd']
}}}
Funkcija {{{MyFn}}} vrati posljednji element, imamo sortiranje prema zadnjem slovu.
{{{
alist.sort() ## correct
alist = blist.sort() ## NO incorrect, sort() returns None
}}}
prvi red sortira listu, argumenti su isti kao kod funkcije {{{sorted}}}.
!! zadatak 3
Napravi listu od 20 cijelih brojeva s random generatorom randint, vrijednosti cijelih brojeva u listi moraju biti od 1do 6.
Napravi histogram, tj. prebroji koliko ima 1, 2,...6.
<hr>
Dictionaries koriste ključ (key) pomoću kojeg dobivaju vrijednost. U primjeru se printaju imena (member) i njihova pripadna vrijednost.
{{{
relatives ={"Lisa" : "daughter", "Bart" : "son", "Marge" : "mother",
"Homer" : "father", "Santa" : "dog"}
for member in relatives.keys():
print member, "is a", relatives[member]
}}}
!! zadatak 4
Napravi još jedan rječnik s godinama i printaj ga s pripadnim imenom.
Modificiraj rječnik tako da rječnik u sebi sadrži listu kao vrijednost, npr {{{relatives={"Lisa":["daughter",9]} }}}, isprintaj za svaki ključ pripadne vrijednosti.
1. Napiši program koji broji riječi u rečenici.
2. Modificiraj program tako da pročita rečenicu iz filea.
3. Napiši program koji računa srednju duljinu riječi u rečenici.
4. wc program na Unixu (word count) analizira file, i izračuna broj linija,
riječi i znakova (uključujući i prazan prostor - whitespace). Napišite svoju
verziju programa, ulaz neka bude file i neka ispiše broj linija, riječi i
znakova.
!problem 1
Pogledajte file checksize.py
program uzima 1 argument, koji mora biti direktorij.
Program pretraži cijeli direktorij zapisan u varijabli root1 i isprinta sve file-ove veće od 1Mb.
funkcija
''os.path.walk(root1, checksize1, bigfiles)''
poziva funkciju checksize1 koja provjerava veličinu file-a i posprema je u listu bigfiles.
*Modificirajte program tako da radi s direktorijima, i neka printa sortiranu listu direktorija u Kb.
!problem 2
Modificirajte program findprogvtk.py tako da pronalazi program koji upisete kao prvi argument, npr.
''python findprogvtk.py ls'' mora isprintati gdje se nalazi naredba ''ls''.
!problem 3
Primjer argumenata na komandnoj liniji, ako je prvi argument "english" dobivamo engleski, "german" njemački, inače pita koji želimo jezik:
{{{
import sys
if (len(sys.argv) > 1):
if( sys.argv[1] == 'english' ):
print "Hello World!"
elif( sys.argv[1] == 'german' ):
print "Guten Tag Welt!"
else:
print "Which language?"
print "Welche sprache?"
else:
print "Which language do you want?"
print "Welch sprache wisst du?"
}}}
Za naprednije korištenje argumenata vidi [[optarg]] primjer. Slijedeći kod, izlista sve fileove u direktoriju, odabere python fileove i onda ih pozipa u vjezba5.zip file.
{{{
import os
import fnmatch
import commands
ol=os.listdir(".");
pyfiles=fnmatch.filter(ol,'*.py');
cmd = 'zip -j ' + 'vjezba5' + ' ' + ' '.join(pyfiles)
print "Command I'm going to do:" + cmd
(status, output) = commands.getstatusoutput(cmd)
# If command had a problem (status is non-zero),
# print its output to stderr and exit.
if status:
sys.stderr.write(output)
sys.exit(1)
}}}
Napravite program mzip, koji ima opciju -z za mjenjanje (definiranje) imena zip file-a i zadnji argument je "pattern" fileova koje če staviti u zip file. Npr.
{{{
./mzip *.py -- pospremi sve .py u vjezba.txt
./mzip -z vjezba5 v*.py -- pospremi sve v*.py u vjezba5.zip
itd...
}}}
!problem 4
Napišite program unpack.py koji ''odpakirava'' file napravljen pomoću programa
pack.py.
Ako se na početku linije nalazi string "###file: ", to znaci da slijedeće linije treba pospremiti u prvi file, izuzevši ovu liniju. Slijedeća linija sa stringom "###file: " označava početak slijedećeg file-a. itd...
Vidi privremene opaske, iz knjiga u [[scripting python]] dijelu, poglavlje
ex pp 118.
!problem 1
Napišite rezultat programa
{{{
class Bozo:
def __init__(self, value):
print "Creating a Bozo from:", value
self.value = 2 * value
def clown(self, x):
print "Clowning:", x
print x * self.value
return x + self.value
def main():
print "Clowning around now."
c1 = Bozo(3)
c2 = Bozo(4)
print c1.clown(3)
print c2.clown(c1.clown(2))
main()
}}}
!problem 2
!!Uvod: specijalne metode
Navedene metode mogu se prikayati kao operatori pomoću tzv. ''overload''-a:
* {{{ __init__(self [, args])}}}: Constructor.
* {{{__del__(self)}}}: Destructor (seldom used since Python oers automatic garbage collection).
* {{{ __str__(self)}}}: String representation for nice printing of the object. Called by print or str.
* {{{__repr__(self)}}}: String representation of an instance, called by repr, and intended for recreation of the instance. That is, eval(repr(a)) should equal a. While the aim of {{{__str__}}} is pretty print, {{{__repr__}}} should (ideally) provide the contents of the whole object in valid Python syntax
* {{{__getitem__(self, i)}}}: Used for subscripting {{{b = a[i]}}}. An assignment like {{{a[i] = v}}} is defined by {{{a.__setitem__(self, i, v)}}}, and removing an instance, like {{{del a[i]}}}, is defined through {{{a.__delitem__(self, i)}}}. These three methods are also used for slices. In that case, i is a slice object with read-only attributes start, stop, and step. A statement like {{{b = a[1:n:2]}}} invokes {{{a.__getitem__(i)}}}, with i.start as 1, i.stop as n, and i.step as 2. If the start, stop, or step parameter is omitted in the slice syntax, the corresponding attribute in the slice object is None. Testing if i is a slice object can be done by isinstance(i, slice). Multi-dimensional indices are supported: {{{b = a[:-2, 1:, p:q, 3]}}} calls {{{a.__getitem__(i)}}} with i as a 4-tuple, where the first three elements are slice objects and the last is an integer. A slice object can be created by slice(start,stop,step).
*{{{__add__(self, b)}}}: Defines {{{self + b}}}. For example, {{{c = a + b}}} implies the call {{{c = a.__add__(b)}}}. Subtraction, multiplication, division, and raising to a power are dened by similar methods named {{{ __sub__}}}, {{{__mul__}}}, {{{__div__}}}, and {{{__pow__ }}}(a**b and pow(a,b) call {{{a.__pow__(b))}}}.
Napravi klasu ~Vec3D koja zna sklarni produkt, vektorski produkt,
normu, zbrajanje, oduzimanje, etc. Funkcionalnost je prikazana primjerom
{{{
>>> from Vec3D import Vec3D
>>> u = Vec3D(1, 0, 0) # (1,0,0) vector
8.5. Classes 397
>>> v = Vec3D(0, 1, 0)
>>> str(u) # pretty print
'(1, 0, 0)'
>>> repr(u) # u = eval(repr(u))
'Vec3D(1, 0, 0)'
>>> u.len() # Eucledian norm
1.0
>>> u[1] # subscripting
0.0
>>> v[2]=2.5 # subscripting w/assignment
>>> print u**v # cross product
(0, -2.5, 1) # (output applies __str__)
>>> u+v # vector addition
Vec3D(1, 1, 2.5) # (output applies __repr__)
>>> u-v # vector subtraction
Vec3D(1, -1, -2.5)
>>> u*v # inner (scalar, dot) product
0.0
}}}
Za brze račune treba koristiti ~NumPy array, klasa je samo za ilustraciju.
Template:
{{{
class Vec3D:
def __init__(self,*vv):
self.v1=[]
for it in vv:
#print it
self.v1.append(it)
def __str__(self):
mstr= '('+str(self.v1)+')'
return mstr
def __repr__(self):
mstr='Vect('+str(self.v1)+')'
return mstr
def __add__(self, b):
sum=Vec3D(0,0,0);
for i in range(3):
sum[i]=self.v1[i]+b[i]
return sum;
def __getitem__(self, i):
return self.v1[i];
def __setitem__(self, i,b):
self.v1[i]=b;
if __name__ == '__main__':
v1=Vec3D(0,1,2)
print str(v1)
print v1, repr(v1)
}}}
Ne gleda se posebno na komponente vektora, već se stvara lista v1.
!problem 3
Modificiraj ~Vec3D klasu iz prethodnog zadatka tako da operatori (npr. +) rade i sa skalarima:
{{{
u = Vec3D(1, 0, 0)
v = Vec3D(0, -0.2, 8)
a = 1.2
u+v # vector addition
a+v # scalar plus vector, yields (1.2, 1, 9.2)
v+a # vector plus scalar, yields (1.2, 1, 9.2)
}}}
Na isti način moguće je napraviti operacije a-v, v-a, a*v, v*a, and v/a (a/v nije definiran).
!Problem 4
Napravi klasu za "imenik":
{{{
from phones import *
class Phones:
def __init__(self,phonel):
self.phl=phonel;
def getEntry(self,i):
return self.phl[i];
def addEntryEnd(self,nstr):
self.phl.append(nstr);
def printPhones(self):
for name,phone in self.phl:
print name,' ',phone;
mph=Phones(phonelist);
mph.printPhones();
}}}
gdje je {{{phones.py}}} lista:
{{{
phonelist = [ ['Meyers, Chris', '343-4349'],
['Smith, Robert', '689-1234'],
['Jones, Janet', '483-5432'],
['Barnhart, Ralph','683-2341'],
['Nelson, Eric', '485-2689'],
['Prefect, Ford', '987-6543'],
['Zigler, Mary', '567-8901'],
['Smith, Bob', '689-1234'] ]
}}}
Klasa treba omoguciti lakse programiranje GUI-a za imenik, vidi Dovršiti GUI za imenik. http://www.irb.hr/users/maks/pdf/UITkinter.pdf
Treba napraviti funkcije
{{{ def addEntry () :
def updateEntry() :
def deleteEntry() :
}}}
koje nisu ovisne o GUI-u, i rade samo s listom.
Dovršiti GUI za imenik. http://www.irb.hr/users/maks/pdf/UITkinter.pdf
Napisati "event", npr '<Double-1>' i napisati funkciju poput loadEntry. Dupli click u listbox-u učita odabrano ime i telefon.
Vidi str. 28-35
Kopiraj phone.py i tkphone.py iz http://www.irb.hr/users/maks/vjezbe5
Napraviti zadatke na str. 38 skripte
!Window Titles
This section discusses conventions for window titles of both primary and secondary windows. Italics indicate text you must replace; window titles themselves do not use the italic font style.
Title Text in Primary Windows
The title text in a primary window should use the format Document or Object Name - Application Name. Figure 105 shows the proper format for the window title, with the document title appearing first. If the title is truncated, the most important part of the title remains visible.
Figure 105 Proper Format for Window Title
[img[4window2.gif]]
!Primary Window Title Format
In primary windows, begin the window title text with a name describing the contents of the window, followed by a space, a hyphen, another space, and the application name.
Title Text in Secondary Windows
The title text in secondary windows should use the format Descriptive Name - Application Name. The Application Name is optional but should be included if users might not otherwise recognize the source of the secondary window.
In secondary windows, begin the window title with a name describing the contents of the window. Follow that text with the application name when users might be unclear which application is associated with the window.
The secondary window in the following figure is often displayed by the ~MetalButler calendar program while users are focused on some other task. Therefore, its window title includes the application name.
Figure 106 Secondary Window Title With Optional Application Name
!Secondary Window Title With Application Name
The secondary window shown in Figure 107 is displayed immediately after a user tries to save a new file with an existing name. The source of the alert box is clear. Therefore, the window title does not include the application name.
Click here to view the corresponding code for Figure 107 (also available on the book's companion ~CD-ROM).
Figure 107 Secondary Window Title Without Optional Application Name
Secondary Window Title Without Application Name
Title Text in Internal Windows
The title text in internal windows should use the format Descriptive Name or Descriptive Name - Tool Name. For an example of the title text in an internal window, see Figure 102.
In an internal window, provide the window title with a name describing the contents of the window. Since the backing window makes the application name clear, you can omit the application name. If there is a tool within the application, you can use the format Descriptive Name - Tool Name.
Java Look and Feel Design Guidelines, second edition.
Mathematica has been a great success in very broadly handling all kinds of formal technical systems and knowledge.
But what about everything else? What about all other systematic knowledge? All the methods and models, and data, that exists?
Fifty years ago, when computers were young, people assumed that they’d quickly be able to handle all these kinds of things.
And that one would be able to ask a computer any factual question, and have it compute the answer.
But it didn’t work out that way. Computers have been able to do many remarkable and unexpected things. But not that.
I’d always thought, though, that eventually it should be possible. And a few years ago, I realized that I was finally in a position to try to do it.
I had two crucial ingredients: Mathematica and NKS. With Mathematica, I had a symbolic language to represent anything—as well as the algorithmic power to do any kind of computation. And with NKS, I had a paradigm for understanding how all sorts of complexity could arise from simple rules.
But what about all the actual knowledge that we as humans have accumulated?
A lot of it is now on the web—in billions of pages of text. And with search engines, we can very efficiently search for specific terms and phrases in that text.
But we can’t compute from that. And in effect, we can only answer questions that have been literally asked before. We can look things up, but we can’t figure anything new out.
So how can we deal with that? Well, some people have thought the way forward must be to somehow automatically understand the natural language that exists on the web. Perhaps getting the web semantically tagged to make that easier.
But armed with Mathematica and NKS I realized there’s another way: explicitly implement methods and models, as algorithms, and explicitly curate all data so that it is immediately computable.
It’s not easy to do this. Every different kind of method and model—and data—has its own special features and character. But with a mixture of Mathematica and NKS automation, and a lot of human experts, I’m happy to say that we’ve gotten a very long way.
But, OK. Let’s say we succeed in creating a system that knows a lot, and can figure a lot out. How can we interact with it?
The way humans normally communicate is through natural language. And when one’s dealing with the whole spectrum of knowledge, I think that’s the only realistic option for communicating with computers too.
Of course, getting computers to deal with natural language has turned out to be incredibly difficult. And for example we’re still very far away from having computers systematically understand large volumes of natural language text on the web.
But if one’s already made knowledge computable, one doesn’t need to do that kind of natural language understanding.
All one needs to be able to do is to take questions people ask in natural language, and represent them in a precise form that fits into the computations one can do.
Of course, even that has never been done in any generality. And it’s made more difficult by the fact that one doesn’t just want to handle a language like English: one also wants to be able to handle all the shorthand notations that people in every possible field use.
I wasn’t at all sure it was going to work. But I’m happy to say that with a mixture of many clever algorithms and heuristics, lots of linguistic discovery and linguistic curation, and what probably amount to some serious theoretical breakthroughs, we’re actually managing to make it work.
Pulling all of this together to create a true computational knowledge engine is a very difficult task.
It’s certainly the most complex project I’ve ever undertaken. Involving far more kinds of expertise—and more moving parts—than I’ve ever had to assemble before.
And—like Mathematica, or NKS—the project will never be finished.
But I’m happy to say that we’ve almost reached the point where we feel we can expose the first part of it.
Source: [[Wolfram Blog : Wolfram:Alpha Is Coming!|http://blog.wolfram.com/2009/03/05/wolframalpha-is-coming/]]
The Xerox Alto was an early personal computer developed at Xerox PARC in 1973. It was the first computer to use the desktop metaphor and graphical user interface (GUI).
It was not a commercial product, but several thousand units were built and were heavily used at PARC and at several universities for many years. The Alto greatly influenced the design of personal computers in the following decades, notably the Macintosh and the first Sun workstations. It is now very rare and a valuable collector's item.
[img[Xerox_Alto.jpg]]
!History
The Alto was first conceptualized in 1972 in a memo written by Butler Lampson, inspired by the ~On-Line System (NLS) developed by Douglas Engelbart at SRI, and was designed primarily by Chuck Thacker. Manufacturing was sub-contracted to Clement Designlabs, whose team included Carl J. Clement, Ken Campbell and Fred Stengel [1]. An initial run of 80 units was produced by Clement Designlabs, working with Tony Ciuffini and Rick Nevinger at Xerox El Segundo, who were responsible for installing the Alto’s electronics. Due to the success of the pilot run, the team went on to produce approximately 2000 units over the next ten years [1].
! Architecture
The Alto had 128 (expandable to 512) kB of main memory and a hard disk with a removable 2.5 MB cartridge, all housed in a cabinet about the size of a small refrigerator. The Alto's CPU was a very innovative microcoded processor which used microcode for most of the I/O functions rather than hardware. The microcode machine had 16 tasks, one of which executed the normal instruction set (which was rather like a Data General Nova), with the others used for the display, memory refresh, disk, network, and other I/O functions. As an example, the bit map display controller was little more than a 16-bit shift register; microcode was used to fetch display refresh data from main memory and put it in the shift register.
Apart from an Ethernet connection, the Alto's only common output device was a bi-level (black and white) CRT display with a tilt-and-swivel base, mounted in "portrait" orientation rather than the more common "landscape" orientation. Its input devices were a custom detachable keyboard, a three-button mouse, and an optional 5-key chord keyset. The last two items had been introduced by SRI's ~On-Line System; while the mouse was an instant success among Alto users, the chord keyset never became popular.
Source: [[Xerox Alto - Wikipedia, the free encyclopedia|http://en.wikipedia.org/wiki/Xerox_Alto]]
Napravi program video poker pomoću kocke. Grafički program prikazat će 5 kocki, pomoću koji se igra poker.
Osnovna pravila su:
* Početni ulog je \$100.
* Svako dijeljenje je \$10, iznos se oduzima na početku dijeljenja
* Prvo se dobiva niz od pet kocki sa slučajnim vrijednostima.
* Možemo ponoviti dijeljenje za sve ili odabrane kocke.
* na kraju dijeljenja ulog se izračunava prema shemi:
|Dva para|Two Pairs| 5|
|triling |Three of a Kind| 8|
|Ful|Full House (A Pair and a Three of a Kind)| 12|
|poker|Four of a Kind| 15|
|skala|Straight (1–5 or 2–6)| 20|
|flush|Five of a Kind |30|
Iznos novaca se stalno prikazuje
* Igra je gotova ako se ostane bez novaca
* Igra se može završiti ako se odabere quit
* U svakom trenutku se pokazuje koji su mogući odgovori korisnika
!Objekti
Klasa Dice imati će informacije o kocki. Nekoliko očiglednih operacije klase:
*constructor početni skup
*rollAll pridruži random vrijednost svakoj od 5 kocki
*roll pridruži random vrijednosti podskupu kocki, a ostale se ne mjenjaju
*values Return the current values of the five dice.
*score Return the score for the dice.
We can also think of the entire program as an object. Let’s call the class ~PokerApp
!!!Implementing Dice
The Dice class implements a collection of dice, which are just changing numbers. The obvious representation
is to use a list of five ints. Our constructor needs to create a list and assign some initial values.
{{{
class Dice:
def __init__(self):
self.dice = [0]*5
self.rollAll()
}}}
We need methods to roll selected dice and also to roll all of the dice. For example, roll([0,3,4]) would roll the dice in positions 0, 3 and 4
of the dice list. We just need a loop that goes through the parameter and generates a new random value for each position.
{{{
def roll(self, which):
for pos in which:
self.dice[pos] = randrange(1,7)
}}}
Next, we can use roll to implement rollAll as follows:
{{{
def rollAll(self):
self.roll(range(5))
}}}
I used range(5) to generate a list of all the indexes.
The values function is used to return the values of the dice so that they can be displayed. Another
one-liner suffices.
{{{
def values(self):
return self.dice[:]
}}}
Notice that I created a copy of the dice list by slicing it. That way, if a Dice client modifies the list that it gets back from values, it will not affect the original copy stored in the Dice object. This defensive programming prevents other parts of the code from accidently messing with our object
One simple way of checking the hand is to generate a list of the counts of each value. That is, counts[i] will be the number of times that the value i occurs in dice. If the dice are: [3,2,5,2,3] then the count list would be [0,0,2,2,0,1,0]. Notice that counts[0] will always be zero, since dice values are in the range 1–6.
{{{
def score(self):
# Create the counts list
counts = [0] * 7
for value in self.dice:
counts[value] = counts[value] + 1
# score the hand
if 5 in counts:
return "Five of a Kind", 30
elif 4 in counts:
return "Four of a Kind", 15
elif (3 in counts) and (2 in counts):
return "Full House", 12
elif 3 in counts:
return "Three of a Kind", 8
elif not (2 in counts) and (counts[1]==0 or counts[6] == 0):
return "Straight", 20
elif counts.count(2) == 2:
return "Two Pairs", 5
else:
return "Garbage", 0
}}}
At this point, we could try out the Dice class to make sure that it is working correctly. Here is a short
interaction showing some of what the class can do:
{{{
>>> from dice import Dice
>>> d = Dice()
>>> d.values()
[6, 3, 3, 6, 5]
>>> d.score()
(’Two Pairs’, 5)
>>> d.roll([4])
>>> d.values()
[6, 3, 3, 6, 4]
>>> d.roll([4])
>>> d.values()
[6, 3, 3, 6, 3]
>>> d.score()
(’Full House’, 12)
}}}
!Implementing ~PokerApp
Initially, we know that the ~PokerApp will need to keep track of the dice, the amount of money, and
some user interface. Let’s initialize these values in the constructor.
{{{
class PokerApp:
def __init__(self):
self.dice = Dice()
self.money = 100
self.interface = PokerInterface()
}}}
To run the program, we will create an instance of this class and call its run method. Basically, the program will loop, allowing the user to continue playing hands until he or she is either out of money or chooses to quit.
{{{
def run(self):
while self.money >= 10 and self.interface.wantToPlay():
self.playRound()
self.interface.close()
}}}
program has now been pushed into the playRound method
This code only really handles the scoring aspect of a round.
{{{
Each round will consist of a series of rolls. Based on these
rolls, the program will have to adjust the player’s score.
def playRound(self):
self.money = self.money - 10
self.interface.setMoney(self.money)
self.doRolls()
result, score = self.dice.score()
self.interface.showResult(result, score)
self.money = self.money + score
self.interface.setMoney(self.money)
}}}
Initially, all of the dice will be rolled. Then we need a loop that continues rolling user-selected dice until either the user chooses to quit rolling or the limit of three rolls is reached. Let’s use a local variable rolls to keep track of how many times the dice have been rolled. Obviously, displaying the dice and getting the the list of dice to roll must come from interaction with the user through interface.
{{{
def doRolls(self):
self.dice.rollAll()
roll = 1
self.interface.setDice(self.dice.values())
toRoll = self.interface.chooseDice()
while roll < 3 and toRoll != []:
self.dice.roll(toRoll)
roll = roll + 1
self.interface.setDice(self.dice.values())
if roll < 3:
toRoll = self.interface.chooseDice()
}}}
!A ~Text-Based UI
First, let’s tweak our ~PokerApp class a bit so that the user interface is supplied as a parameter to the
constructor.
{{{
class PokerApp:
def __init__(self, interface):
self.dice = Dice()
self.money = 100
self.interface = interface
}}}
Then we can easily create versions of the poker program using different interfaces.
Here is a complete ~TextInterface class using this approach:
{{{
# file: textpoker.py
class TextInterface:
def __init__(self):
print "Welcome to video poker."
........................................
def close(self):
print "\nThanks for playing!"
def showResult(self, msg, score):
print "%s. You win $%d." % (msg, score)
def chooseDice(self):
return input("Enter list of which to change ([] to stop) ")
}}}
Using this interface, we can test out our ~PokerApp program to see if we have implemented a correct
model. Here is a complete program making use of the modules that we have developed:
{{{
# textpoker.py -- video dice poker using a text-based interface.
from pokerapp import PokerApp
from textinter import TextInterface
inter = TextInterface()
app =PokerApp(inter)
app.run()
}}}
Running this program, we get a rough but useable interaction.
{{{
Welcome to video poker.
Do you wish to try your luck? y
You currently have $90.
Dice: [6, 4, 4, 2, 4]
Enter list of which to change ([] to stop) [0,4]
Dice: [1, 4, 4, 2, 2]
Enter list of which to change ([] to stop) [0]
Dice: [2, 4, 4, 2, 2]
Full House. You win $12.
You currently have $102.
Do you wish to try your luck? y
You currently have $92.
Dice: [5, 6, 4, 4, 5]
Enter list of which to change ([] to stop) [1]
Dice: [5, 5, 4, 4, 5]
Enter list of which to change ([] to stop) []
Full House. You win $12.
You currently have $104.
}}}
!Command Line Arguments in Python - A Tutorial
Only one import statement is necessary:
Code:
{{{
#!/usr/bin/env python
from optparse import OptionParser
}}}
The first thing we would like to do is set a usage string. This will be displayed when the user supplies '-h' or '- -help' as an option. We then create a parser object with this usage string.
Code:
{{{
use = "Usage: %prog [options] argument1 argument2"
parser = OptionParser(usage = use)
}}}
%prog will print out the name of the file being run. A usage string is not required and will default to:
Usage: tut.py [options]
Our next step is to add options to the parser.
Code:
{{{
parser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False, help="Set mode to verbose.")
parser.add_option("-f", "--filename", dest="write" metavar="FILE", help="write output to FILE"),
}}}
The first two arguments of add_option give the short and longhand calls for the option. 'dest=STRING' stores a variable with the name of the given string. 'metavar' gives the name of the expected argument to be received with the option. 'metavar' should be used when you do not want to store a variable as a boolean. Parser will print an error and exit if the expected argument is not given. Finally, 'help' stores the string that will be printed given the argument {{{--help}}}.
If the option -h is supplied with our program, the output would be:
{{{
Usage: tut.py [options] argument1 argument2
Options:
-h, --help show this help message and exit
-v, --verbose Set mode to verbose.
-f FILE, --filename=FILE write output to FILE
}}}
The final step is to parse the options and arguments into variables we can use later.
Code:
{{{
options, args = parser.parse_args()
}}}
After this statement, 'options' will contain the variables we set to store when we added options to parser. 'args' will contain the arguments listed after all options.
After all options and arguments have been parsed, it would make sense to be able to access the information. Options are accessed through parser.<variable name> and arguments are accessed through an index in the array, 'args'.
Code:
{{{
if options.verbose:
print "Mode is set to verbose!"
print options.write
print args[0]
print args[1]
}}}
Given the input:
Code:
{{{
./test.py -v -f my_file ARG1 ARG1
}}}
The output would be:
{{{
Mode is set to verbose!
my_file
ARG1
ARG2
}}}
Source: [[Python Tutorial - Handling Command Line Arguments|http://forum.codecall.net/tutorials/16496-python-tutorial-handling-command-line-arguments.html]]
!! IF
{{{
if answer == ’copy’:
copyfile = ’tmp.copy’
elif answer == ’run’ or answer == ’execute’:
run = True
elif answer == ’quit’ and not eps < eps_crit:
quit = True
else:
print ’Invalid answer’, answer
}}}
The test {{{if var}}} returns false if var is {{{None}}}, a numeric type with value 0, a
boolean with value True, an empty string (’’), an empty list ([]), an empty
tuple (()), or an empty dictionary ({}). Otherwise, the if test is true.
!!While Loops.
The syntax of a while loop is illustrated next:
{{{
r = 0; dr = 0.1
while r <= 10:
print ’sin(%.1f)=%g’ % (r, math.sin(r))
r += dr
}}}
The range function only generates integers so for loops with a real number
counter is better implemented as while loops (which was illustrated above
for a counter r running as 0, 0.1, 0.2, . . . , 9.9, 10).
The while var condition evaluates to true or false in the same way as the
if var test.
!For Loops.
Looping over a list is done with the for statement:
{{
{for arg in sys.argv[1:]:
#work with string arg}}}
An explicit integer index can also be used:
{{{
for i in range(1, len(sys.argv), 1):
# work with string sys.argv[i]
}}}
!!break
{{{
f = open(filename, ’r’)
while 1:
line = f.readline()
if line == ’’: # empty string means end of file
break # jump out of while loop
# process line
...
}}}
!!continue
{{{
files = os.listdir(os.curdir) # all files/dirs in current dir.
for file in files:
if not os.path.isfile(file): # not a regular file, continue with next
continue
<process file>
}}}
!FILE
{{{
infilename = ’.myprog.cpp’
infile = open(infilename, ’r’) # open file for reading
# read the file into a list of lines:
lines = infile.readlines()
for line in lines:
# process line
# read the file line by line:
for line in infile:
# process line
# alternative reading, line by line:
while 1:
line = infile.readline()
if not line: break
# process line
# load the file into a string instead:
filestr = infile.read()
# read n characters (bytes) into a string:
chunck = infile.read(n)
infile.close()
}}}
!Format
{{{
>>> r=1.2
>>> s=math.sin(r)
>>> # print adds a space between comma-separated arguments:
>>> print "sin(", r, ")=", s
sin( 1.2 )= 0.932039085967
>>> # use + between the strings to avoid any extra space:
>>> print ’sin(’ + str(r) + ’)=’ + str(s)
sin(1.2)=0.932039085967
>>> # format control via the printf-like syntax:
>>> print "sin(%g)=%12.5e" % (r,s)
sin(1.2)= 9.32039e-01
>>> # format control via variable interpolation:
>>> print ’sin(%(r)g)=%(s)12.5e’ % vars()
sin(1.2)= 9.32039e-01
%d: an integer
%5d: an integer written in a field of width 5 chars
%-5d: an integer written in a field of width 5 chars,
%g: a float variable written in %f or %e notation
%e: a float variable written in scientific notation
%E: as %e, but upper case E is used for the exponent
%G: as %g, but upper case E is used for the exponent
%11.3e : a float variable written in scientific notation with 3 decimals in a field of width 11 chars
%.3e: a float variable written in scientific notation with 3 decimals in a field of minimum width
%5.1f : a float variable written in fixed decimal notation with 1 decimal in a field of width 5 chars
%.3f : a float variable written in fixed decimal form with 3 decimals in a field of minimum width
%s : a string
%-20s : a string adjusted to the left in a field of width 20 chars
}}}
!!Exercise 3.5. Pack a collection of files.
Make a script pack.py that packs a collection of files into a single file. For example, running the script with the command-line arguments
file1.dat file2.dat mysim.dat res.dat
packs the three files file1.dat, file2.dat, and mysim.dat into a single text file res.dat. Such a tool is convenient when transferring a large number of files over the Internet (in email, for instance). Also write an “inverse” script unpack.py that recovers the original files, given the name of a single text file like res.dat as command-line argument. Hints: To recognize the beginning of a new file (say) some_filename.c in the packed file, one can, e.g., insert an extra line with a syntax like
{{{
###file: some_filename.c
}}}
This line then acts as delimiter between the individual files. There are several
methods to check if a line in the file matches the special syntax ###file: ...
and to extract the name of the file (here some_filename.c):
* 1st alternative:
{{{
if line[:9] == ’###file: ’:
filename = line[9:]
}}}
* 2nd alternative:
{{{
if line.find(’###file: ’) != -1:
filename = line.split()[1] # 2nd word on line
}}}
* 3rd alternative (using regular expressions):
{{{
m = re.search(’^###file: (.*)$’, line)
if m:
filename = m.group(1)
# get rid of blanks:
filename = filename.strip()
}}}
!!Exercise 3.7. Check if your system has a specific program.
Write a function taking a program name as argument and returning true if the program is found in one of the directories in the PATH environment variable and false otherwise. This function is useful for determining whether a specific program is available or not. Hint: Read Chapter 3.2.5.
{{{
import os
program = 'vtk' # a sample program to search for
pathdirs = os.environ['PATH'].split(os.pathsep)
for dir in pathdirs:
if os.path.isdir(dir): # skip non-existing directories
if os.path.isfile(os.path.join(dir,program)):
program_path = dir; break
try: # program was found if program_path is defined
print program, ’found in’, program_path
except:
print program, ’not found’
}}}
A trivial example of using os.path.walk is to write out the names of all files in all subdirectories in your home tree. You can try this code segment out in an interactive Python shell to get a feeling for how os.path.walk works:
{{{
def ls(arg, dir, files):
print dir,’has the files’,files
os.path.walk(os.environ[’HOME’], ls, None)
}}}
find files larger than 1Mb.
{{{
import os
def checksize1(arg, dir, files):
for file in files:
filepath = os.path.join(dir, file)
if os.path.isfile(filepath):
size = os.path.getsize(filepath)
if size > 1000000:
msg = '%.2fMb %s' % (size/1000000.0, filepath)
arg.append(msg)
bigfiles = []
root = os.environ['HOME']
os.path.walk(root, checksize1, bigfiles)
for fileinfo in bigfiles:
print fileinfo
}}}
Shell nam omogućava izvršavanje komandi pod unixom, iako se smatra primitivnim uglavnom podržava jednostavne oblike programiranja, različita podešavanja pomoću fileova u HOME direktoriju (fileovi .tcshhrc, .bashrc itd.. ovisno o ljusci "shell"), definiranje varijabli, mogućnosti i programiranje ovise o odabranoj ljusci (sh, tcsh, bash...). shell pod linuxom je vrlo često bash (GNU ~Bourne-Again ~SHell), možete provjeriti naredbom
{{{
env | grep -i shell
}}}
kod bash ljuske rezultat je {{{SHELL=/bin/bash}}}.
! bash
Konfiguracijski fileovi su: {{{ .bashrc , .profile i .bash_profile}}}. U {{{.bashrc}}} stavljamo tzv. aliase, npr. za {{{demo.py}}}.
Redosljed kojim bash čita redosljedom /etc/profile, ~/.bash_profile, ~/.bash_login i ~/.profile, pored toga pročita i ~/.bashrc. Tradicionalna sh ljuska koristi samo /etc/profile i ~/.profile.
Sve što možemo izvršiti na komandnoj liniji, npr ''ls'' kako bi izlistali fileove, možemo napisati u file.
Npr. ls -la upišemo u lsla.sh file, ''bash lsla.sh'' nam izlista sve direktorije i fileove. Pod ~UNIXom (komandom
''chmod u+x lsla.sh '' omogućavamo da file možemo izvršiti, komandom ''./lsla.sh'').
''alias'' nam omogućava da pozovemo neku komandu s drugim imenom, npr ''alias la=ls -la'' definira komandu la.
Umjesto da pišemo svaki put aliase i varijable koje su nam potrebne možemo ih napisati u file ''~/.bashrc'',
gdje znak ''~'' zamjenjuje ''HOME'' direktorij definiran pomoću varijable ''HOME''. Vrijednost varijable možemo vidjeti komandom ''$echo $HOME'', to vrijedi za bilo koju vraijablu (npr. echo $PATH).
U file ''~/.bashrc'' npr. možemo napisati slijedeće linije:
{{{
# some more ls aliases
alias ll='ls -l'
alias la='ls -A'
#alias l='ls -CF'
alias wxdemo='python ~/tmp/wxPython/demo.py'
export PYTHONSTARTUP='/home/maks/.pythonrc.py'
}}}
prva linija je komentar, zatim dva aliasa, opet komentar, onda alias koji poziva python i pokreće python program demo.py, i na kraju definiramo vraijablu koja definira file koji je za python analog ''.bashrc''.
Saznamo gdje se nalazi demo.py s naredbom locate: {{{ locate demo.py}}}. Na Ubuntu distribuciji imamo
{{{
locate demo.py | grep -i wx
/usr/share/doc/wx2.6-examples/examples/wxPython/demo.py
/usr/share/doc/wx2.8-examples/examples/wxPython/demo.py
}}}
Napomena: Potrebno je napraviti logout i ponovo login, ili {{{source ~/.bashrc}}} kako bi se aktivirao novi alias. Nakon toga dovoljno je napisati {{{wxdemo}}}.
Primjer kompliciranije upotrebe bash ljuske:
{{{
or i in /opt/*/bin /usr/local/bin ; do
test -d $i || continue
echo $PATH | grep -wq "$i" && continue
PATH=$PATH:$i
export PATH
done
}}}
tražimo ''bin'' direktorije u ''/opt'' i ''/usr/local/bin'', zatim ih dodamo ako nisu u PATH varijabli.
! python
podešavanje python ljuske
__pythonrc.py__
{{{
# Definiraj "export PYTHONSTARTUP=/home/USERNAME/.pythonrc.py" in .bashrc.
# PYTHONSTARTUP ne smije imati "~", napisati puni ''path'' za home direktorij
import atexit
import os
import readline
import rlcompleter
readline.parse_and_bind('tab: complete')
historyPath = os.path.expanduser("~/.pyhistory")
def save_history(historyPath=historyPath):
import readline
readline.write_history_file(historyPath)
if os.path.exists(historyPath):
readline.read_history_file(historyPath)
atexit.register(save_history)
del os, atexit, readline, rlcompleter, save_history, historyPath
}}}
__unix.py__
{{{
import os
def wrap(f):
"""
Wraps a function so that if it's entered *by itself*
in the interpreter without ()'s, it gets called anyway
"""
class W:
def __init__(self, f):
self.f = f
def __repr__(self):
x =apply(self.f)
if x:
return repr(x)
else:
return ''
return W(f)
def ls():
"""
Produces a directory listing of the current directory.
Usage: ls
"""
os.system('/bin/ls -Fs')
return None
ls = wrap(ls)
def ll():
"""
Produces a "ls -ltr" directory listing of the current directory.
Usage: ll
"""
os.system('/bin/ls -ltr')
return None
ll = wrap(ll)
def pwd():
"""
Changes the working python directory for the interpreter.
Usage: pwd (no parens needed)
"""
return os.getcwd()
pwd = wrap(pwd)
def cd (directory):
"""
Changes the working python directory for the interpreter.
Usage: cd(directory) where 'directory' is a string
"""
os.chdir(directory)
return
}}}
TODO
* pp 416 vjezbe za klase u scripting python
* dovrsi projekt [[dicePoker]]
[[scripting python]]
from py4science.pdf
! Standard library
{{{
> > > import math
> > > math.log(10)
2.3025850929940459
> > > math.sin(math.pi)
1.2246063538223773e-16
}}}
Promjena imena //math// u //m//
{{{
# Appreviate the module name: m is an alias
> > > import math as m
> > > m.cos(2*m.pi)
1.0
# Import just the names you need
> > > from math import exp, log
> > > log(exp(1))
1.0
# Import everything - use with caution!
> > > from math import *
> > > sin(2*pi*10)
-2.4492127076447545e-15
}}}
! help naredba
{{{
> > > dir(math)
[’__doc__’, ’__file__’, ’__name__’, ’acos’, ’asin’, ’atan’, ’atan2’, ,,,,
> > > help(math.sin)
Help on built-in function sin:
sin(...)
sin(x)
Return the sine of x (measured in radians).
> > > help(math)
Help on module math:
NAME
math
FILE
/usr/local/lib/python2.3/lib-dynload/math.so
DESCRIPTION
This module is always available. It provides access to the
mathematical functions defined by the C standard.
FUNCTIONS
acos(...)
acos(x)
Return the arc cosine (measured in radians) of x.
asin(...)
asin(x)
Return the arc sine (measured in radians) of x.
}}}
!Struktura programa
U wx pythonu moramo napraviti subklasu App, nasljednika wx.App ili koristiti ~PySimpleApp
!!! ~PySimpleApp
{{{
import wx
app=wx.PySimpleApp()
frame=wx.Frame(parent=None,id=-1,title='simple ...',size=(400,200))
frame.Show()
app.MainLoop()
}}}
!!! subklasa App
{{{
import wx
class App(wx.App):
def OnInit(self):
frame=wx.Frame(parent=None,title='bare')
frame.Show()
return True
app=App()
app.MainLoop()
}}}
__Opaska__ frame mora biti inicijaliziran u funkciji {{{OnInit}}}, jer klasa {{{wx.App}}} mora postojati kako bi se frame mogao napraviti.
!!Frame klasa
Glavni "prozor" aplikacije prikazan je ovom klasom, npr. jednostavni editor implementiran preko {{{wx.TextCtrl}}} klase
{{{
ID_NEW = wx.ID_NEW
ID_OPEN = wx.ID_OPEN
ID_REVERT = wx.ID_REVERT
ID_CLOSE = wx.ID_CLOSE
ID_SAVE = wx.ID_SAVE
ID_SAVEAS = wx.ID_SAVEAS
ID_PRINT = wx.ID_PRINT
ID_EXIT = wx.ID_EXIT
ID_ABOUT=wx.ID_ABOUT
class XFrame(wx.Frame):
def __init__(self, parent,title):
wx.Frame.__init__(self, parent,title='simple ed',size=(600,400),style=wx.DEFAULT_FRAME_STYLE)
self.control=wx.TextCtrl(self,style=wx.TE_MULTILINE)
self.CreateStatusBar()
menubar=self.MenbuBars()
self.doBind()
self.SetMenuBar(menubar)
def MenbuBars(self):
menubar=wx.MenuBar(style=wx.MENU_TEAROFF)
m_file=wx.Menu()
menubar.Append(m_file,"&File")
m_file.Append(ID_NEW,"&New \tCtrl+N'","New file")
m_file.Append(ID_OPEN,"&Open... \tCtrl+O","Open file")
m_file.AppendSeparator()
m_file.Append(ID_CLOSE,"&Close \tCtrl+W","Close file")
m_file.AppendSeparator()
m_file.Append(ID_SAVE, '&Save... \tCtrl+S',
'Save file')
m_file.Append(ID_SAVEAS, 'Save &As \tCtrl+Shift+S',
'Save file with new name')
m_file.AppendSeparator()
m_file.Append(ID_EXIT,"E&xit","Exit now")
mh=wx.Menu()
mh.Append(ID_ABOUT,"&About","Find all about ...")
mh.AppendSeparator()
mh.Append(ID_EXIT,"&Help","Help for ed")
menubar.Append(mh,"&Help")
return menubar
def doBind(self):
self.Bind(wx.EVT_MENU,self.OnQuit, id=ID_EXIT)
def OnQuit(self,event):
self.Close()
}}}
Promjenimo klasu {{{App}}} tako da prvi argument predstavlja ime file-a koji se otvori u editoru
{{{
class App(wx.App):
def OnInit(self):
frame=XFrame(parent=None,title='bare')
if len(sys.argv) > 1 :
try:
frame.control.LoadFile(sys.argv[1])
except:
print "Can't load file", sys.argv[1]
exit(1)
frame.Show()
return True
}}}
Dodatne promjene za otvaranje fileova:
{{{
def doBind(self):
self.Bind(wx.EVT_MENU,self.OnQuit, id=ID_EXIT)
self.Bind(wx.EVT_MENU,self.OnOpen, id=ID_OPEN)
self.Bind(wx.EVT_MENU,self.OnNew, id=ID_NEW)
def OnQuit(self,event):
self.Close()
def OnOpen(self,event):
print "Open file"
filed= wx.FileDialog(self,message = 'Choose an image to open',
defaultDir = '',defaultFile = '',wildcard = '*.py;*.txt',
style = wx.OPEN)
if filed.ShowModal() == wx.ID_OK:
self.path = filed.GetPath()
self.control.LoadFile(self.path)
def OnNew(self,event):
self.control.Clear()
}}}
I napokon dodajmo funkciju za About
{{{
def OnAbout(self,event):
wx.MessageBox(message="Napisano na satovima KS",caption="KS simple ed",style=wx.OK|wx.CENTRE)
}}}
naravno treba napisati Bind u funkciji doBind.
!~PyAlaMode
Možemo pronaći source naredbom locate, tj. {{{locate PyAlaMode.py}}}
{{{
"""PyAlaMode is a programmer's editor."""
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id: PyAlaMode.py 26212 2004-03-15 13:42:37Z PKO $"
__revision__ = "$Revision: 26212 $"[11:-2]
import wx
from wx import py
import os
import sys
class App(wx.App):
"""PyAlaMode standalone application."""
def __init__(self, filename=None):
self.filename = filename
wx.App.__init__(self, redirect=False)
def OnInit(self):
wx.InitAllImageHandlers()
self.frame = py.editor.EditorNotebookFrame(filename=self.filename)
self.frame.Show()
self.SetTopWindow(self.frame)
return True
def main(filename=None):
if not filename and len(sys.argv) > 1:
filename = sys.argv[1]
if filename:
filename = os.path.realpath(filename)
app = App(filename)
app.MainLoop()
if __name__ == '__main__':
main()
}}}
Skripta {{{pyalamode}}} poziva ovaj editor na slijedeći način:
{{{
#!/usr/bin/python2.5
from wx.py.PyAlaMode import main
main()
}}}
dakle iz direktorija "wx/py" učitava se "~PyAlaMode.py".