├── .gitignore
├── Mimas_Cassini.jpg
├── README.md
├── commandLineBuild.sh
├── doc
├── binaryfiles
│ ├── adt
│ │ ├── FixedRecordList.html
│ │ ├── FixedRecordSeq.html
│ │ ├── VariableRecordSeq.html
│ │ └── index.html
│ └── index.html
├── ch2oobasics
│ ├── GradeBook$.html
│ ├── Student.html
│ ├── bank
│ │ ├── Account.html
│ │ ├── Address.html
│ │ ├── Bank.html
│ │ ├── BankMain$.html
│ │ ├── Customer.html
│ │ ├── Loan.html
│ │ ├── PhoneNumber.html
│ │ └── package.html
│ └── package.html
├── guigraphics
│ ├── AnimationExample$$Swarmer.html
│ ├── AnimationExample$.html
│ ├── FirstGUI$.html
│ ├── KeyboardMouseInput$.html
│ ├── index.html
│ ├── v1
│ │ ├── DrawingMain$.html
│ │ └── index.html
│ └── v2
│ │ ├── DrawRectangle.html
│ │ ├── DrawText.html
│ │ ├── DrawTransform$.html
│ │ ├── DrawTransform.html
│ │ ├── Drawable.html
│ │ ├── Drawing.html
│ │ ├── DrawingMain$.html
│ │ └── index.html
├── hashtables
│ ├── adt
│ │ ├── ChainingHashMap$.html
│ │ ├── ChainingHashMap.html
│ │ ├── HashingMethods$.html
│ │ ├── OpenAddressingHashMap$.html
│ │ ├── OpenAddressingHashMap.html
│ │ ├── ProbingMethods$.html
│ │ ├── TestHashingOrder$.html
│ │ └── index.html
│ └── index.html
├── heaps
│ ├── adt
│ │ ├── BinaryHeapPriorityQueue.html
│ │ └── index.html
│ ├── index.html
│ └── util
│ │ ├── Sorts$.html
│ │ └── index.html
├── index.html
├── index.js
├── index
│ ├── index-a.html
│ ├── index-b.html
│ ├── index-c.html
│ ├── index-d.html
│ ├── index-f.html
│ ├── index-g.html
│ ├── index-i.html
│ ├── index-l.html
│ ├── index-m.html
│ ├── index-p.html
│ ├── index-q.html
│ ├── index-r.html
│ ├── index-s.html
│ ├── index-t.html
│ ├── index-v.html
│ └── index-w.html
├── iostreams
│ ├── ByteCopy$.html
│ ├── LoanPattern$.html
│ ├── ReadBytes$.html
│ ├── ReadBytesTry$.html
│ ├── ReadBytesTryFinally$.html
│ ├── ReadWriteBinary$.html
│ ├── SerializationCode$.html
│ ├── SerializationTest$.html
│ ├── Student.html
│ ├── XMLCode$.html
│ ├── drawing
│ │ ├── Commands$.html
│ │ ├── DrawJulia$.html
│ │ ├── DrawJulia$JuliaActor.html
│ │ ├── DrawJulia$Line.html
│ │ ├── DrawJulia$LineActor.html
│ │ ├── DrawJulia$LineResult.html
│ │ ├── DrawJulia$MakeImage$.html
│ │ ├── DrawJulia.html
│ │ ├── DrawMandelbrot$.html
│ │ ├── DrawMandelbrot.html
│ │ ├── DrawMaze$.html
│ │ ├── DrawMaze.html
│ │ ├── DrawRectangle$.html
│ │ ├── DrawRectangle.html
│ │ ├── DrawText$.html
│ │ ├── DrawText.html
│ │ ├── DrawTransform$.html
│ │ ├── DrawTransform.html
│ │ ├── Drawable$.html
│ │ ├── Drawable.html
│ │ ├── Drawing$.html
│ │ ├── Drawing.html
│ │ ├── DrawingMain$.html
│ │ └── index.html
│ └── index.html
├── lib
│ ├── MaterialIcons-Regular.eot
│ ├── MaterialIcons-Regular.ttf
│ ├── MaterialIcons-Regular.woff
│ ├── abstract_type.svg
│ ├── arrow-down.png
│ ├── arrow-right.png
│ ├── class.png
│ ├── class.svg
│ ├── class_big.png
│ ├── class_comp.svg
│ ├── class_diagram.png
│ ├── class_to_object_big.png
│ ├── constructorsbg.gif
│ ├── conversionbg.gif
│ ├── defbg-blue.gif
│ ├── defbg-green.gif
│ ├── diagrams.css
│ ├── diagrams.js
│ ├── filter_box_left.png
│ ├── filter_box_left2.gif
│ ├── filter_box_right.png
│ ├── filterbg.gif
│ ├── filterboxbarbg.gif
│ ├── filterboxbarbg.png
│ ├── filterboxbg.gif
│ ├── fullcommenttopbg.gif
│ ├── index.css
│ ├── index.js
│ ├── jquery-ui.js
│ ├── jquery.js
│ ├── jquery.layout.js
│ ├── jquery.mousewheel.min.js
│ ├── jquery.panzoom.min.js
│ ├── lato-v11-latin-100.eot
│ ├── lato-v11-latin-100.ttf
│ ├── lato-v11-latin-100.woff
│ ├── lato-v11-latin-regular.eot
│ ├── lato-v11-latin-regular.ttf
│ ├── lato-v11-latin-regular.woff
│ ├── modernizr.custom.js
│ ├── navigation-li-a.png
│ ├── navigation-li.png
│ ├── object.png
│ ├── object.svg
│ ├── object_big.png
│ ├── object_comp.svg
│ ├── object_diagram.png
│ ├── object_to_class_big.png
│ ├── object_to_trait_big.png
│ ├── object_to_type_big.png
│ ├── open-sans-v13-latin-regular.eot
│ ├── open-sans-v13-latin-regular.ttf
│ ├── open-sans-v13-latin-regular.woff
│ ├── ownderbg2.gif
│ ├── ownerbg.gif
│ ├── ownerbg2.gif
│ ├── package.png
│ ├── package.svg
│ ├── package_big.png
│ ├── packagesbg.gif
│ ├── permalink.png
│ ├── ref-index.css
│ ├── remove.png
│ ├── scheduler.js
│ ├── selected-implicits.png
│ ├── selected-right-implicits.png
│ ├── selected-right.png
│ ├── selected.png
│ ├── selected2-right.png
│ ├── selected2.png
│ ├── signaturebg.gif
│ ├── signaturebg2.gif
│ ├── source-code-pro-v6-latin-700.eot
│ ├── source-code-pro-v6-latin-700.ttf
│ ├── source-code-pro-v6-latin-700.woff
│ ├── source-code-pro-v6-latin-regular.eot
│ ├── source-code-pro-v6-latin-regular.ttf
│ ├── source-code-pro-v6-latin-regular.woff
│ ├── template.css
│ ├── template.js
│ ├── tools.tooltip.js
│ ├── trait.png
│ ├── trait.svg
│ ├── trait_big.png
│ ├── trait_comp.svg
│ ├── trait_diagram.png
│ ├── trait_to_object_big.png
│ ├── type.png
│ ├── type_big.png
│ ├── type_diagram.png
│ ├── type_to_object_big.png
│ ├── typebg.gif
│ ├── unselected.png
│ └── valuemembersbg.gif
├── linkedlist
│ ├── adt
│ │ ├── Cons.html
│ │ ├── ImmutableSLList$.html
│ │ ├── ImmutableSLList.html
│ │ ├── ListQueue.html
│ │ ├── ListStack.html
│ │ ├── MutableDLList.html
│ │ ├── MutableDLList2.html
│ │ ├── MutableSLList.html
│ │ ├── MutableSLList2$.html
│ │ ├── MutableSLList2.html
│ │ ├── MyNil$.html
│ │ ├── Queue.html
│ │ ├── SinglyLinkedList.html
│ │ ├── Stack.html
│ │ └── index.html
│ └── index.html
├── mapset
│ ├── SimpleCode$.html
│ ├── drawing
│ │ ├── Commands$.html
│ │ ├── DrawRectangle.html
│ │ ├── DrawText.html
│ │ ├── DrawTransform$.html
│ │ ├── DrawTransform.html
│ │ ├── Drawable.html
│ │ ├── Drawing.html
│ │ ├── DrawingMain$.html
│ │ └── index.html
│ └── index.html
├── moretrees
│ ├── adt
│ │ ├── ImmutableAVLTreeMap$.html
│ │ ├── ImmutableAVLTreeMap.html
│ │ ├── IntersectionOctree$$IntersectionObject.html
│ │ ├── IntersectionOctree$$ParamCalc.html
│ │ ├── IntersectionOctree$.html
│ │ ├── IntersectionOctree.html
│ │ ├── OrderStatTreeBuffer.html
│ │ ├── RayTracing$$Ray.html
│ │ ├── RayTracing$$Sphere.html
│ │ ├── RayTracing$.html
│ │ └── index.html
│ └── index.html
├── multithreading1
│ ├── Account.html
│ ├── AccountSync.html
│ ├── RandomCodeSegments$$A.html
│ ├── RandomCodeSegments$$B.html
│ ├── RandomCodeSegments$.html
│ ├── SimpleExample$.html
│ ├── SimpleThreadGUI$.html
│ ├── ThreadBlockGUI$.html
│ ├── WeeksWeather$.html
│ ├── WeeksWeatherFor$.html
│ ├── actorexamples
│ │ ├── AskActor$$AskName$.html
│ │ ├── AskActor$$AskOf.html
│ │ ├── AskActor$.html
│ │ ├── AskActor.html
│ │ ├── AskPattern$.html
│ │ ├── ChildActor$$SimpleMessage$.html
│ │ ├── ChildActor$$ToParent$.html
│ │ ├── ChildActor$.html
│ │ ├── ChildActor.html
│ │ ├── CountDown$.html
│ │ ├── CountDownActor$$Count.html
│ │ ├── CountDownActor$$StartCounting.html
│ │ ├── CountDownActor$.html
│ │ ├── CountDownActor.html
│ │ ├── HierarchyExample$.html
│ │ ├── LifecycleChild$$SimpleMessage$.html
│ │ ├── LifecycleChild$$Throw$.html
│ │ ├── LifecycleChild$.html
│ │ ├── LifecycleChild.html
│ │ ├── LifecycleParent.html
│ │ ├── ParentActor$$Cascade$.html
│ │ ├── ParentActor$.html
│ │ ├── ParentActor.html
│ │ ├── RouterExample$$Complex.html
│ │ ├── RouterExample$$JuliaActor.html
│ │ ├── RouterExample$$Line.html
│ │ ├── RouterExample$$LineActor.html
│ │ ├── RouterExample$$LineResult.html
│ │ ├── RouterExample$$MakeImage.html
│ │ ├── RouterExample$.html
│ │ ├── SimpleExample$$SimpleActor.html
│ │ ├── SimpleExample$.html
│ │ ├── SupervisorExample$.html
│ │ └── index.html
│ ├── drawing
│ │ ├── Commands$.html
│ │ ├── DrawJulia$JuliaActor.html
│ │ ├── DrawJulia$Line.html
│ │ ├── DrawJulia$LineActor.html
│ │ ├── DrawJulia$LineResult.html
│ │ ├── DrawJulia$MakeImage$.html
│ │ ├── DrawJulia.html
│ │ ├── DrawMandelbrot.html
│ │ ├── DrawMaze.html
│ │ ├── DrawRectangle.html
│ │ ├── DrawText.html
│ │ ├── DrawTransform$.html
│ │ ├── DrawTransform.html
│ │ ├── Drawable.html
│ │ ├── Drawing.html
│ │ ├── DrawingMain$.html
│ │ └── index.html
│ └── index.html
├── multithreading2
│ ├── CountAtomic$.html
│ ├── FutureJoining$.html
│ ├── NonAtomicLocking$.html
│ ├── ParallelFactorials$.html
│ ├── ReadTimeout$.html
│ ├── ReadTimeout2$.html
│ ├── ReadTimeout3$.html
│ ├── ThreadJoining$.html
│ ├── WaitCounting$.html
│ ├── WaitCountingSafe$.html
│ └── index.html
├── networking
│ ├── Datagram$.html
│ ├── DoClient$.html
│ ├── DoServer$.html
│ ├── RandomNetworkingCode$.html
│ ├── chat
│ │ ├── ChatClient$.html
│ │ ├── ChatServer$.html
│ │ ├── RMIClient$.html
│ │ ├── RMIServer$.html
│ │ ├── RemoteClient.html
│ │ ├── RemoteServer.html
│ │ └── index.html
│ ├── drawing
│ │ ├── CollaborationServer.html
│ │ ├── Collaborator.html
│ │ ├── Commands$.html
│ │ ├── DrawJulia$.html
│ │ ├── DrawJulia$JuliaActor.html
│ │ ├── DrawJulia$Line.html
│ │ ├── DrawJulia$LineActor.html
│ │ ├── DrawJulia$LineResult.html
│ │ ├── DrawJulia$MakeImage.html
│ │ ├── DrawJulia.html
│ │ ├── DrawMandelbrot$.html
│ │ ├── DrawMandelbrot.html
│ │ ├── DrawMaze$.html
│ │ ├── DrawMaze.html
│ │ ├── DrawRectangle$.html
│ │ ├── DrawRectangle.html
│ │ ├── DrawText$.html
│ │ ├── DrawText.html
│ │ ├── DrawTransform$.html
│ │ ├── DrawTransform.html
│ │ ├── Drawable$.html
│ │ ├── Drawable.html
│ │ ├── Drawing$.html
│ │ ├── Drawing.html
│ │ ├── DrawingMain$.html
│ │ ├── RemoteCollaborationServer.html
│ │ ├── RemoteCollaborator.html
│ │ ├── SketchEllipse.html
│ │ ├── SketchLine.html
│ │ ├── SketchPath.html
│ │ ├── SketchRect.html
│ │ ├── Sketchable.html
│ │ └── index.html
│ └── index.html
├── oobasics
│ ├── GradeBook$.html
│ ├── Student.html
│ ├── bank
│ │ ├── Account.html
│ │ ├── Address.html
│ │ ├── Bank.html
│ │ ├── BankMain$.html
│ │ ├── Customer.html
│ │ ├── Loan.html
│ │ ├── PhoneNumber.html
│ │ └── index.html
│ └── index.html
├── oodetails
│ ├── Account$.html
│ ├── Account.html
│ ├── AssignmentOps$.html
│ ├── Customer.html
│ ├── Instructor.html
│ ├── MutableVect2D$.html
│ ├── MutableVect2D.html
│ ├── MutableVect2D_a$.html
│ ├── MutableVect2D_a.html
│ ├── MutableVect2D_b$.html
│ ├── MutableVect2D_b.html
│ ├── Student.html
│ ├── StudentStuff$.html
│ ├── Vect2D$.html
│ ├── Vect2D.html
│ ├── Vect2D_a$.html
│ ├── Vect2D_a.html
│ ├── Vect2D_b$.html
│ ├── Vect2D_b.html
│ ├── index.html
│ └── students
│ │ ├── Student$.html
│ │ ├── Student.html
│ │ └── index.html
├── package.html
├── polymorphism
│ ├── BasicAbstraction$.html
│ ├── Blender.html
│ ├── Cherry.html
│ ├── Female.html
│ ├── Fruit.html
│ ├── FruitFunctions$.html
│ ├── Mother.html
│ ├── Parent.html
│ ├── Person.html
│ ├── Skin.html
│ ├── Sorting$.html
│ ├── Sorts$.html
│ ├── StreetLight.html
│ ├── StreetLightColor$.html
│ ├── StringComparison$$CharInStrComp.html
│ ├── StringComparison$$CntCharInStrComp.html
│ ├── StringComparison$.html
│ ├── StructuralTypes$.html
│ ├── index.html
│ ├── shape1
│ │ ├── Circle.html
│ │ ├── MutableRectangle.html
│ │ ├── MutableSquare.html
│ │ ├── Rectangle.html
│ │ ├── Shape.html
│ │ ├── ShapeFunctions$.html
│ │ ├── Square.html
│ │ └── index.html
│ ├── shape2
│ │ ├── Circle.html
│ │ ├── Rectangle.html
│ │ ├── Shape.html
│ │ └── index.html
│ ├── shape3
│ │ ├── Circle.html
│ │ ├── Rectangle.html
│ │ ├── Shape.html
│ │ └── index.html
│ ├── shapeabstract
│ │ ├── Shape.html
│ │ └── index.html
│ ├── supershape
│ │ ├── Rectangle.html
│ │ ├── Shape.html
│ │ └── index.html
│ ├── themepark
│ │ ├── ToDValues.html
│ │ ├── UseToD$.html
│ │ └── index.html
│ └── themepark2
│ │ ├── ToDValues$.html
│ │ ├── ToDValues.html
│ │ └── index.html
├── priorityqueues
│ ├── adt
│ │ ├── PriorityQueue.html
│ │ ├── SortedListPQWithRemove.html
│ │ ├── SortedListPriorityQueue.html
│ │ └── index.html
│ ├── drawing
│ │ ├── CollaborationServer.html
│ │ ├── Collaborator.html
│ │ ├── Commands$.html
│ │ ├── DrawBouncingBalls$$Ball.html
│ │ ├── DrawBouncingBalls$.html
│ │ ├── DrawBouncingBalls.html
│ │ ├── DrawCellSim$.html
│ │ ├── DrawCellSim.html
│ │ ├── DrawJulia$.html
│ │ ├── DrawJulia$JuliaActor.html
│ │ ├── DrawJulia$Line.html
│ │ ├── DrawJulia$LineActor.html
│ │ ├── DrawJulia$LineResult.html
│ │ ├── DrawJulia$MakeImage.html
│ │ ├── DrawJulia.html
│ │ ├── DrawMandelbrot$.html
│ │ ├── DrawMandelbrot.html
│ │ ├── DrawMaze$.html
│ │ ├── DrawMaze.html
│ │ ├── DrawRectangle$.html
│ │ ├── DrawRectangle.html
│ │ ├── DrawText$.html
│ │ ├── DrawText.html
│ │ ├── DrawTransform$.html
│ │ ├── DrawTransform.html
│ │ ├── Drawable$.html
│ │ ├── Drawable.html
│ │ ├── Drawing$.html
│ │ ├── Drawing.html
│ │ ├── DrawingMain$.html
│ │ ├── RemoteCollaborationServer.html
│ │ ├── RemoteCollaborator.html
│ │ ├── SketchEllipse.html
│ │ ├── SketchLine.html
│ │ ├── SketchPath.html
│ │ ├── SketchRect.html
│ │ ├── Sketchable.html
│ │ └── index.html
│ └── index.html
├── recursion
│ ├── drawing
│ │ ├── Clickable.html
│ │ ├── CollaborationServer.html
│ │ ├── Collaborator.html
│ │ ├── Commands$.html
│ │ ├── DrawBouncingBalls$$Ball.html
│ │ ├── DrawBouncingBalls$.html
│ │ ├── DrawBouncingBalls.html
│ │ ├── DrawCellSim$.html
│ │ ├── DrawCellSim.html
│ │ ├── DrawGraph$.html
│ │ ├── DrawGraph.html
│ │ ├── DrawJulia$.html
│ │ ├── DrawJulia$JuliaActor.html
│ │ ├── DrawJulia$Line.html
│ │ ├── DrawJulia$LineActor.html
│ │ ├── DrawJulia$LineResult.html
│ │ ├── DrawJulia$MakeImage.html
│ │ ├── DrawJulia.html
│ │ ├── DrawMandelbrot$.html
│ │ ├── DrawMandelbrot.html
│ │ ├── DrawMaze$.html
│ │ ├── DrawMaze.html
│ │ ├── DrawRectangle$.html
│ │ ├── DrawRectangle.html
│ │ ├── DrawText$.html
│ │ ├── DrawText.html
│ │ ├── DrawTransform$.html
│ │ ├── DrawTransform.html
│ │ ├── Drawable$.html
│ │ ├── Drawable.html
│ │ ├── Drawing$.html
│ │ ├── Drawing.html
│ │ ├── DrawingMain$.html
│ │ ├── RemoteCollaborationServer.html
│ │ ├── RemoteCollaborator.html
│ │ ├── SketchEllipse.html
│ │ ├── SketchLine.html
│ │ ├── SketchPath.html
│ │ ├── SketchRect.html
│ │ ├── Sketchable.html
│ │ └── index.html
│ ├── index.html
│ └── util
│ │ ├── Formula$.html
│ │ ├── Sorting$.html
│ │ └── index.html
├── recursionrefresh
│ ├── CodeSegments$.html
│ └── index.html
├── regexparser
│ ├── CodeSegments$.html
│ ├── drawing
│ │ ├── Clickable.html
│ │ ├── CollaborationServer.html
│ │ ├── Collaborator.html
│ │ ├── Commands$.html
│ │ ├── DrawBouncingBalls$$Ball.html
│ │ ├── DrawBouncingBalls$.html
│ │ ├── DrawBouncingBalls.html
│ │ ├── DrawCellSim$.html
│ │ ├── DrawCellSim.html
│ │ ├── DrawGraph$.html
│ │ ├── DrawGraph.html
│ │ ├── DrawJulia$.html
│ │ ├── DrawJulia$JuliaActor.html
│ │ ├── DrawJulia$Line.html
│ │ ├── DrawJulia$LineActor.html
│ │ ├── DrawJulia$LineResult.html
│ │ ├── DrawJulia$MakeImage.html
│ │ ├── DrawJulia.html
│ │ ├── DrawMandelbrot$.html
│ │ ├── DrawMandelbrot.html
│ │ ├── DrawMaze$.html
│ │ ├── DrawMaze.html
│ │ ├── DrawRectangle$.html
│ │ ├── DrawRectangle.html
│ │ ├── DrawText$.html
│ │ ├── DrawText.html
│ │ ├── DrawTransform$.html
│ │ ├── DrawTransform.html
│ │ ├── Drawable$.html
│ │ ├── Drawable.html
│ │ ├── Drawing$.html
│ │ ├── Drawing.html
│ │ ├── DrawingMain$.html
│ │ ├── RemoteCollaborationServer.html
│ │ ├── RemoteCollaborator.html
│ │ ├── SketchEllipse.html
│ │ ├── SketchLine.html
│ │ ├── SketchPath.html
│ │ ├── SketchRect.html
│ │ ├── Sketchable.html
│ │ └── index.html
│ ├── index.html
│ └── util
│ │ ├── Formula$.html
│ │ ├── Formula.html
│ │ └── index.html
├── scalalang
│ ├── ShippingCalc$.html
│ ├── ShippingCalcS$.html
│ └── index.html
├── spatialtrees
│ ├── adt
│ │ ├── BruteForceNeighborVisitor.html
│ │ ├── KDTreeNeighborVisitor$Node.html
│ │ ├── KDTreeNeighborVisitor.html
│ │ ├── NeighborVisitor.html
│ │ ├── QuadtreeNeighborVisitor.html
│ │ ├── RegularGridNeighborVisitor.html
│ │ └── index.html
│ └── index.html
├── stackqueue
│ ├── adt
│ │ ├── ArrayQueue.html
│ │ ├── ArrayStack.html
│ │ ├── Queue.html
│ │ ├── Stack.html
│ │ └── index.html
│ ├── drawing
│ │ ├── Commands$.html
│ │ ├── DrawMaze.html
│ │ ├── DrawRectangle.html
│ │ ├── DrawText.html
│ │ ├── DrawTransform$.html
│ │ ├── DrawTransform.html
│ │ ├── Drawable.html
│ │ ├── Drawing.html
│ │ ├── DrawingMain$.html
│ │ └── index.html
│ ├── index.html
│ └── util
│ │ ├── RPNCalc$.html
│ │ └── index.html
├── test
│ ├── binaryfiles
│ │ ├── adt
│ │ │ ├── TestFixedRecordList.html
│ │ │ ├── TestFixedRecordSeq.html
│ │ │ ├── TestVariableRecordSeq.html
│ │ │ └── index.html
│ │ └── index.html
│ ├── hashtables
│ │ ├── adt
│ │ │ ├── TestChainingHashMap.html
│ │ │ ├── TestOpenAddressingHashMap.html
│ │ │ └── index.html
│ │ └── index.html
│ ├── index.html
│ ├── linkedlist
│ │ ├── adt
│ │ │ ├── TestImmutableSLList.html
│ │ │ ├── TestListQueue.html
│ │ │ ├── TestListStack.html
│ │ │ ├── TestMutableDLList.html
│ │ │ ├── TestMutableSLList.html
│ │ │ ├── TestSinglyLinkedList.html
│ │ │ └── index.html
│ │ └── index.html
│ ├── moretrees
│ │ ├── adt
│ │ │ ├── TestImmutableAVLTreeMap.html
│ │ │ ├── TestOrderStatTreeBuffer.html
│ │ │ └── index.html
│ │ └── index.html
│ ├── priorityqueues
│ │ ├── adt
│ │ │ ├── TestSortedListPriorityQueue.html
│ │ │ └── index.html
│ │ └── index.html
│ └── stackqueue
│ │ ├── AllTests.html
│ │ ├── adt
│ │ ├── TestArrayQueue.html
│ │ ├── TestArrayStack.html
│ │ └── index.html
│ │ ├── index.html
│ │ └── util
│ │ ├── TestRPNCalc.html
│ │ └── index.html
└── trees
│ ├── adt
│ ├── ImmutableTreeMap$.html
│ ├── ImmutableTreeMap.html
│ ├── TreeMap$.html
│ ├── TreeMap.html
│ ├── index.html
│ └── trees
│ │ ├── adt
│ │ ├── TreeMapRecur$.html
│ │ ├── TreeMapRecur.html
│ │ └── index.html
│ │ └── index.html
│ ├── drawing
│ ├── Clickable.html
│ ├── CollaborationServer.html
│ ├── Collaborator.html
│ ├── Commands$.html
│ ├── DrawBouncingBalls$$Ball.html
│ ├── DrawBouncingBalls$.html
│ ├── DrawBouncingBalls.html
│ ├── DrawCellSim$.html
│ ├── DrawCellSim.html
│ ├── DrawGraph$.html
│ ├── DrawGraph.html
│ ├── DrawJulia$.html
│ ├── DrawJulia$JuliaActor.html
│ ├── DrawJulia$Line.html
│ ├── DrawJulia$LineActor.html
│ ├── DrawJulia$LineResult.html
│ ├── DrawJulia$MakeImage.html
│ ├── DrawJulia.html
│ ├── DrawMandelbrot$.html
│ ├── DrawMandelbrot.html
│ ├── DrawMaze$.html
│ ├── DrawMaze.html
│ ├── DrawRectangle$.html
│ ├── DrawRectangle.html
│ ├── DrawText$.html
│ ├── DrawText.html
│ ├── DrawTransform$.html
│ ├── DrawTransform.html
│ ├── Drawable$.html
│ ├── Drawable.html
│ ├── Drawing$.html
│ ├── Drawing.html
│ ├── DrawingMain$.html
│ ├── RemoteCollaborationServer.html
│ ├── RemoteCollaborator.html
│ ├── SketchEllipse.html
│ ├── SketchLine.html
│ ├── SketchPath.html
│ ├── SketchRect.html
│ ├── Sketchable.html
│ └── index.html
│ ├── index.html
│ └── util
│ ├── Formula$.html
│ ├── Formula.html
│ └── index.html
├── generateDocs.sh
├── runApp.sh
└── src
├── advscala
├── Distance.scala
├── NestedClasses.scala
├── Vect2D.scala
└── Vect3D.scala
├── binaryfiles
└── adt
│ ├── FixedRecordList.scala
│ ├── FixedRecordSeq.scala
│ └── VariableRecordSeq.scala
├── guigraphics
├── AnimationExample.scala
├── FirstGUI.scala
├── KeyboardMouseInput.scala
├── v1
│ └── DrawingMain.scala
└── v2
│ ├── DrawRectangle.scala
│ ├── DrawText.scala
│ ├── DrawTransform.scala
│ ├── Drawable.scala
│ ├── Drawing.scala
│ └── DrawingMain.scala
├── hashtables
└── adt
│ ├── ChainingHashMap.scala
│ ├── HashMethods.scala
│ ├── OpenAddressingHashMap.scala
│ └── TestHashingOrder.scala
├── heaps
├── adt
│ └── BinaryHeapPriorityQueue.scala
└── util
│ └── Sorts.scala
├── iostreams
├── ByteCopy.scala
├── LoanPattern.scala
├── ReadBytes.scala
├── ReadBytesTry.scala
├── ReadBytesTryFinally.scala
├── ReadWriteBinary.scala
├── SerializationCode.scala
├── SerializationTest.scala
├── XMLCode.scala
└── drawing
│ ├── Commands.scala
│ ├── DrawJulia.scala
│ ├── DrawMandelbrot.scala
│ ├── DrawMaze.scala
│ ├── DrawRectangle.scala
│ ├── DrawText.scala
│ ├── DrawTransform.scala
│ ├── Drawable.scala
│ ├── Drawing.scala
│ └── DrawingMain.scala
├── linkedlist
└── adt
│ ├── ImmutableSLList.scala
│ ├── ListQueue.scala
│ ├── ListStack.scala
│ ├── MutableDLList.scala
│ ├── MutableDLList2.scala
│ ├── MutableSLList.scala
│ ├── MutableSLList2.scala
│ ├── Queue.scala
│ ├── SinglyLinkedList.scala
│ └── Stack.scala
├── mapset
├── SimpleCode.scala
└── drawing
│ ├── Commands.scala
│ ├── DrawRectangle.scala
│ ├── DrawText.scala
│ ├── DrawTransform.scala
│ ├── Drawable.scala
│ ├── Drawing.scala
│ └── DrawingMain.scala
├── moretrees
└── adt
│ ├── ImmutableAVLTreeMap.scala
│ ├── IntersectionOctree.scala
│ ├── OrderStatTreeBuffer.scala
│ └── RayTracing.scala
├── multithreading1
├── Account.scala
├── AccountSync.scala
├── RandomCodeSegments.scala
├── SimpleExample.scala
├── SimpleThreadGUI.scala
├── ThreadBlockGUI.scala
├── WeeksWeather.scala
├── WeeksWeatherFor.scala
├── actorexamples
│ ├── AskActor.scala
│ ├── AskPattern.scala
│ ├── ChildActor.scala
│ ├── CountDown.scala
│ ├── CountDownActor.scala
│ ├── HierarchyExample.scala
│ ├── LifecycleChild.scala
│ ├── LifecycleParent.scala
│ ├── ParentActor.scala
│ ├── RouterExample.scala
│ ├── SimpleExample.scala
│ └── SupervisorExample.scala
└── drawing
│ ├── Commands.scala
│ ├── DrawJulia.scala
│ ├── DrawMandelbrot.scala
│ ├── DrawMaze.scala
│ ├── DrawRectangle.scala
│ ├── DrawText.scala
│ ├── DrawTransform.scala
│ ├── Drawable.scala
│ ├── Drawing.scala
│ └── DrawingMain.scala
├── multithreading2
├── CountAtomic.scala
├── FutureJoining.scala
├── NonAtomicLocking.scala
├── ParallelFactorials.scala
├── ReadTimeout.scala
├── ReadTimeout2.scala
├── ReadTimeout3.scala
├── ThreadJoining.scala
├── WaitCounting.scala
└── WaitCountingSafe.scala
├── networking
├── Datagram.scala
├── DoClient.scala
├── DoServer.scala
├── RandomNetworkingCode.scala
├── chat
│ ├── ChatClient.scala
│ ├── ChatServer.scala
│ ├── RMIClient.scala
│ ├── RMIServer.scala
│ ├── RemoteClient.scala
│ └── RemoteServer.scala
└── drawing
│ ├── CollaborationServer.scala
│ ├── Collaborator.scala
│ ├── Commands.scala
│ ├── DrawJulia.scala
│ ├── DrawMandelbrot.scala
│ ├── DrawMaze.scala
│ ├── DrawRectangle.scala
│ ├── DrawText.scala
│ ├── DrawTransform.scala
│ ├── Drawable.scala
│ ├── Drawing.scala
│ ├── DrawingMain.scala
│ └── Sketchable.scala
├── oobasics
├── GradeBook.scala
├── Student.scala
└── bank
│ ├── Account.scala
│ ├── Address.scala
│ ├── Bank.scala
│ ├── BankMain.scala
│ ├── Customer.scala
│ ├── Loan.scala
│ └── PhoneNumber.scala
├── oodetails
├── Account.scala
├── AssignmentOps.scala
├── MutableVect2D.scala
├── MutableVect2D_a.scala
├── MutableVect2D_b.scala
├── StudentStuff.scala
├── Vect2D.scala
├── Vect2D_a.scala
├── Vect2D_b.scala
└── students
│ └── Student.scala
├── polymorphism
├── BasicAbstraction.scala
├── FruitFunctions.scala
├── Person.scala
├── Sorting.scala
├── Sorts.scala
├── StreetLight.scala
├── StringComparison.scala
├── StructuralTypes.scala
├── shape1
│ ├── MutableRectangle.scala
│ ├── MutableSquare.scala
│ ├── Shape.scala
│ └── ShapeFunctions.scala
├── shape2
│ └── Shape.scala
├── shape3
│ └── Shape.scala
├── shapeabstract
│ └── Shape.scala
├── supershape
│ ├── Rectangle.scala
│ └── Shape.scala
├── themepark
│ ├── ToDValues.scala
│ └── UseToD.scala
└── themepark2
│ └── ToDValues.scala
├── priorityqueues
├── adt
│ ├── PriorityQueue.scala
│ ├── SortedListPQWithRemove.scala
│ └── SortedListPriorityQueue.scala
└── drawing
│ ├── CollaborationServer.scala
│ ├── Collaborator.scala
│ ├── Commands.scala
│ ├── DrawBouncingBalls.scala
│ ├── DrawCellSim.scala
│ ├── DrawJulia.scala
│ ├── DrawMandelbrot.scala
│ ├── DrawMaze.scala
│ ├── DrawRectangle.scala
│ ├── DrawText.scala
│ ├── DrawTransform.scala
│ ├── Drawable.scala
│ ├── Drawing.scala
│ ├── DrawingMain.scala
│ └── Sketchable.scala
├── recursion
├── drawing
│ ├── Clickable.scala
│ ├── CollaborationServer.scala
│ ├── Collaborator.scala
│ ├── Commands.scala
│ ├── DrawBouncingBalls.scala
│ ├── DrawCellSim.scala
│ ├── DrawGraph.scala
│ ├── DrawJulia.scala
│ ├── DrawMandelbrot.scala
│ ├── DrawMaze.scala
│ ├── DrawRectangle.scala
│ ├── DrawText.scala
│ ├── DrawTransform.scala
│ ├── Drawable.scala
│ ├── Drawing.scala
│ ├── DrawingMain.scala
│ └── Sketchable.scala
└── util
│ ├── Formula.scala
│ └── Sorting.scala
├── recursionrefresh
└── CodeSegments.scala
├── regexparser
├── CodeSegments.scala
├── drawing
│ ├── Clickable.scala
│ ├── CollaborationServer.scala
│ ├── Collaborator.scala
│ ├── Commands.scala
│ ├── DrawBouncingBalls.scala
│ ├── DrawCellSim.scala
│ ├── DrawGraph.scala
│ ├── DrawJulia.scala
│ ├── DrawMandelbrot.scala
│ ├── DrawMaze.scala
│ ├── DrawRectangle.scala
│ ├── DrawText.scala
│ ├── DrawTransform.scala
│ ├── Drawable.scala
│ ├── Drawing.scala
│ ├── DrawingMain.scala
│ └── Sketchable.scala
└── util
│ └── Formula.scala
├── scalalang
├── ShippingCalc.scala
└── ShippingCalcS.scala
├── spatialtrees
└── adt
│ ├── BruteForceNeighborVisitor.scala
│ ├── KDTreeNeighborVisitor.scala
│ ├── NeighborVisitor.scala
│ ├── QuadtreeNeighborVisitor.scala
│ └── RegularGridNeighborVisitor.scala
├── stackqueue
├── adt
│ ├── ArrayQueue.scala
│ ├── ArrayStack.scala
│ ├── Queue.scala
│ └── Stack.scala
├── drawing
│ ├── Commands.scala
│ ├── DrawMaze.scala
│ ├── DrawRectangle.scala
│ ├── DrawText.scala
│ ├── DrawTransform.scala
│ ├── Drawable.scala
│ ├── Drawing.scala
│ └── DrawingMain.scala
└── util
│ └── RPNCalc.scala
├── test
├── binaryfiles
│ └── adt
│ │ ├── TestFixedRecordList.scala
│ │ ├── TestFixedRecordSeq.scala
│ │ └── TestVariableRecordSeq.scala
├── hashtables
│ └── adt
│ │ ├── TestChainingHashMap.scala
│ │ └── TestOpenAddressingHashMap.scala
├── linkedlist
│ └── adt
│ │ ├── TestImmutableSLList.scala
│ │ ├── TestListQueue.scala
│ │ ├── TestListStack.scala
│ │ ├── TestMutableDLList.scala
│ │ ├── TestMutableSLList.scala
│ │ └── TestSinglyLinkedList.scala
├── moretrees
│ └── adt
│ │ ├── TestImmutableAVLTreeMap.scala
│ │ └── TestOrderStatTreeBuffer.scala
├── priorityqueues
│ └── adt
│ │ └── TestSortedListPriorityQueue.scala
└── stackqueue
│ ├── AllTests.scala
│ ├── adt
│ ├── TestArrayQueue.scala
│ └── TestArrayStack.scala
│ └── util
│ └── TestRPNCalc.scala
└── trees
├── adt
├── ImmutableTreeMap.scala
├── TreeMap.scala
└── TreeMapRecur.scala
├── drawing
├── Clickable.scala
├── CollaborationServer.scala
├── Collaborator.scala
├── Commands.scala
├── DrawBouncingBalls.scala
├── DrawCellSim.scala
├── DrawGraph.scala
├── DrawJulia.scala
├── DrawMandelbrot.scala
├── DrawMaze.scala
├── DrawRectangle.scala
├── DrawText.scala
├── DrawTransform.scala
├── Drawable.scala
├── Drawing.scala
├── DrawingMain.scala
└── Sketchable.scala
└── util
└── Formula.scala
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # Created by https://www.gitignore.io/api/scala,eclipse
3 |
4 | ### Scala ###
5 | *.class
6 | *.log
7 |
8 | # sbt specific
9 | .cache
10 | .history
11 | .lib/
12 | dist/*
13 | target/
14 | lib_managed/
15 | src_managed/
16 | project/boot/
17 | project/plugins/project/
18 |
19 | # Scala-IDE specific
20 | .scala_dependencies
21 | .worksheet
22 |
23 |
24 | ### Eclipse ###
25 |
26 | .metadata
27 | bin/
28 | tmp/
29 | *.tmp
30 | *.bak
31 | *.swp
32 | *~.nib
33 | local.properties
34 | .settings/
35 | .loadpath
36 | .recommenders
37 |
38 | # Eclipse Core
39 | .project
40 |
41 | # External tool builders
42 | .externalToolBuilders/
43 |
44 | # Locally stored "Eclipse launch configurations"
45 | *.launch
46 |
47 | # PyDev specific (Python IDE for Eclipse)
48 | *.pydevproject
49 |
50 | # CDT-specific (C/C++ Development Tooling)
51 | .cproject
52 |
53 | # JDT-specific (Eclipse Java Development Tools)
54 | .classpath
55 |
56 | # Java annotation processor (APT)
57 | .factorypath
58 |
59 | # PDT-specific (PHP Development Tools)
60 | .buildpath
61 |
62 | # sbteclipse plugin
63 | .target
64 |
65 | # Tern plugin
66 | .tern-project
67 |
68 | # TeXlipse plugin
69 | .texlipse
70 |
71 | # STS (Spring Tool Suite)
72 | .springBeans
73 |
74 | # Code Recommenders
75 | .recommenders/
76 |
77 | .cache-main
78 |
--------------------------------------------------------------------------------
/Mimas_Cassini.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/Mimas_Cassini.jpg
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # OOAbstractDataStructScala
2 |
3 | This is the code repository for the code in "[Object-Orientation, Abstraction, and Data Structures Using Scala](https://www.amazon.com/Object-Orientation-Abstraction-Structures-Textbooks-Computing/dp/149873216X/)".
4 | Video lectures for the material can be found [on YouTube](https://www.youtube.com/playlist?list=PLLMXbkbDbVt8JLumqKj-3BlHmEXPIfR42).
5 |
--------------------------------------------------------------------------------
/commandLineBuild.sh:
--------------------------------------------------------------------------------
1 | scalac -d bin -feature -deprecation -language:reflectiveCalls -cp /home/mlewis/scalafx_2.12.0-M3-8.0.60-R10-SNAPSHOT.jar:/home/mlewis/akka-2.4.7/lib/akka/akka-actor_2.11-2.4.7.jar:/home/mlewis/akka-2.4.7/lib/akka/config-1.3.0.jar:/home/mlewis/workspace/junit-4.12.jar:/home/mlewis/workspace/hamcrest-core-1.3.jar src/*/*.scala src/*/*/*.scala src/*/*/*/*.scala
2 |
--------------------------------------------------------------------------------
/doc/index/index-b.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
26 |
27 |
--------------------------------------------------------------------------------
/doc/index/index-c.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
17 |
ch2oobasics
18 |
19 |
20 |
closeAccount
21 |
22 |
23 |
createAccount
24 |
25 |
29 |
30 |
--------------------------------------------------------------------------------
/doc/index/index-d.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
17 |
18 |
--------------------------------------------------------------------------------
/doc/index/index-f.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
findAccount
15 |
16 |
17 |
findCustomer
18 |
19 |
26 |
27 |
--------------------------------------------------------------------------------
/doc/index/index-g.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
20 |
21 |
--------------------------------------------------------------------------------
/doc/index/index-i.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
17 |
18 |
--------------------------------------------------------------------------------
/doc/index/index-l.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
26 |
27 |
--------------------------------------------------------------------------------
/doc/index/index-m.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
20 |
21 |
--------------------------------------------------------------------------------
/doc/index/index-p.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
PhoneNumber
15 |
16 |
20 |
printGrade
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/doc/index/index-q.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
quizAverage
15 |
16 |
20 |
21 |
--------------------------------------------------------------------------------
/doc/index/index-r.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
removeAccount
15 |
16 |
17 |
removeLoan
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/doc/index/index-s.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
17 |
18 |
--------------------------------------------------------------------------------
/doc/index/index-t.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
testAverage
15 |
16 |
20 |
21 |
--------------------------------------------------------------------------------
/doc/index/index-v.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
17 |
18 |
--------------------------------------------------------------------------------
/doc/index/index-w.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
17 |
18 |
--------------------------------------------------------------------------------
/doc/lib/MaterialIcons-Regular.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/MaterialIcons-Regular.eot
--------------------------------------------------------------------------------
/doc/lib/MaterialIcons-Regular.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/MaterialIcons-Regular.ttf
--------------------------------------------------------------------------------
/doc/lib/MaterialIcons-Regular.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/MaterialIcons-Regular.woff
--------------------------------------------------------------------------------
/doc/lib/arrow-down.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/arrow-down.png
--------------------------------------------------------------------------------
/doc/lib/arrow-right.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/arrow-right.png
--------------------------------------------------------------------------------
/doc/lib/class.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/class.png
--------------------------------------------------------------------------------
/doc/lib/class_big.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/class_big.png
--------------------------------------------------------------------------------
/doc/lib/class_diagram.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/class_diagram.png
--------------------------------------------------------------------------------
/doc/lib/class_to_object_big.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/class_to_object_big.png
--------------------------------------------------------------------------------
/doc/lib/constructorsbg.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/constructorsbg.gif
--------------------------------------------------------------------------------
/doc/lib/conversionbg.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/conversionbg.gif
--------------------------------------------------------------------------------
/doc/lib/defbg-blue.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/defbg-blue.gif
--------------------------------------------------------------------------------
/doc/lib/defbg-green.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/defbg-green.gif
--------------------------------------------------------------------------------
/doc/lib/filter_box_left.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/filter_box_left.png
--------------------------------------------------------------------------------
/doc/lib/filter_box_left2.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/filter_box_left2.gif
--------------------------------------------------------------------------------
/doc/lib/filter_box_right.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/filter_box_right.png
--------------------------------------------------------------------------------
/doc/lib/filterbg.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/filterbg.gif
--------------------------------------------------------------------------------
/doc/lib/filterboxbarbg.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/filterboxbarbg.gif
--------------------------------------------------------------------------------
/doc/lib/filterboxbarbg.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/filterboxbarbg.png
--------------------------------------------------------------------------------
/doc/lib/filterboxbg.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/filterboxbg.gif
--------------------------------------------------------------------------------
/doc/lib/fullcommenttopbg.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/fullcommenttopbg.gif
--------------------------------------------------------------------------------
/doc/lib/lato-v11-latin-100.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/lato-v11-latin-100.eot
--------------------------------------------------------------------------------
/doc/lib/lato-v11-latin-100.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/lato-v11-latin-100.ttf
--------------------------------------------------------------------------------
/doc/lib/lato-v11-latin-100.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/lato-v11-latin-100.woff
--------------------------------------------------------------------------------
/doc/lib/lato-v11-latin-regular.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/lato-v11-latin-regular.eot
--------------------------------------------------------------------------------
/doc/lib/lato-v11-latin-regular.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/lato-v11-latin-regular.ttf
--------------------------------------------------------------------------------
/doc/lib/lato-v11-latin-regular.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/lato-v11-latin-regular.woff
--------------------------------------------------------------------------------
/doc/lib/modernizr.custom.js:
--------------------------------------------------------------------------------
1 | /* Modernizr 2.5.3 (Custom Build) | MIT & BSD
2 | * Build: http://www.modernizr.com/download/#-inlinesvg
3 | */
4 | ;window.Modernizr=function(a,b,c){function u(a){i.cssText=a}function v(a,b){return u(prefixes.join(a+";")+(b||""))}function w(a,b){return typeof a===b}function x(a,b){return!!~(""+a).indexOf(b)}function y(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:w(f,"function")?f.bind(d||b):f}return!1}var d="2.5.3",e={},f=b.documentElement,g="modernizr",h=b.createElement(g),i=h.style,j,k={}.toString,l={svg:"http://www.w3.org/2000/svg"},m={},n={},o={},p=[],q=p.slice,r,s={}.hasOwnProperty,t;!w(s,"undefined")&&!w(s.call,"undefined")?t=function(a,b){return s.call(a,b)}:t=function(a,b){return b in a&&w(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=q.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(q.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(q.call(arguments)))};return e}),m.inlinesvg=function(){var a=b.createElement("div");return a.innerHTML="",(a.firstChild&&a.firstChild.namespaceURI)==l.svg};for(var z in m)t(m,z)&&(r=z.toLowerCase(),e[r]=m[z](),p.push((e[r]?"":"no-")+r));return u(""),h=j=null,e._version=d,e}(this,this.document);
--------------------------------------------------------------------------------
/doc/lib/navigation-li-a.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/navigation-li-a.png
--------------------------------------------------------------------------------
/doc/lib/navigation-li.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/navigation-li.png
--------------------------------------------------------------------------------
/doc/lib/object.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/object.png
--------------------------------------------------------------------------------
/doc/lib/object_big.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/object_big.png
--------------------------------------------------------------------------------
/doc/lib/object_diagram.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/object_diagram.png
--------------------------------------------------------------------------------
/doc/lib/object_to_class_big.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/object_to_class_big.png
--------------------------------------------------------------------------------
/doc/lib/object_to_trait_big.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/object_to_trait_big.png
--------------------------------------------------------------------------------
/doc/lib/object_to_type_big.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/object_to_type_big.png
--------------------------------------------------------------------------------
/doc/lib/open-sans-v13-latin-regular.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/open-sans-v13-latin-regular.eot
--------------------------------------------------------------------------------
/doc/lib/open-sans-v13-latin-regular.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/open-sans-v13-latin-regular.ttf
--------------------------------------------------------------------------------
/doc/lib/open-sans-v13-latin-regular.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/open-sans-v13-latin-regular.woff
--------------------------------------------------------------------------------
/doc/lib/ownderbg2.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/ownderbg2.gif
--------------------------------------------------------------------------------
/doc/lib/ownerbg.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/ownerbg.gif
--------------------------------------------------------------------------------
/doc/lib/ownerbg2.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/ownerbg2.gif
--------------------------------------------------------------------------------
/doc/lib/package.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/package.png
--------------------------------------------------------------------------------
/doc/lib/package_big.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/package_big.png
--------------------------------------------------------------------------------
/doc/lib/packagesbg.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/packagesbg.gif
--------------------------------------------------------------------------------
/doc/lib/permalink.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/permalink.png
--------------------------------------------------------------------------------
/doc/lib/ref-index.css:
--------------------------------------------------------------------------------
1 | /* fonts */
2 | @font-face {
3 | font-family: 'Source Code Pro';
4 | font-style: normal;
5 | font-weight: 400;
6 | src: url('source-code-pro-v6-latin-regular.eot');
7 | src: local('Source Code Pro'), local('SourceCodePro-Regular'),
8 | url('source-code-pro-v6-latin-regular.eot?#iefix') format('embedded-opentype'),
9 | url('source-code-pro-v6-latin-regular.woff') format('woff'),
10 | url('source-code-pro-v6-latin-regular.ttf') format('truetype');
11 | }
12 | @font-face {
13 | font-family: 'Source Code Pro';
14 | font-style: normal;
15 | font-weight: 700;
16 | src: url('source-code-pro-v6-latin-700.eot');
17 | src: local('Source Code Pro Bold'), local('SourceCodePro-Bold'),
18 | url('source-code-pro-v6-latin-700.eot?#iefix') format('embedded-opentype'),
19 | url('source-code-pro-v6-latin-700.woff') format('woff'),
20 | url('source-code-pro-v6-latin-700.ttf') format('truetype');
21 | }
22 |
23 | body {
24 | font-size: 10pt;
25 | font-family: Arial, sans-serif;
26 | }
27 |
28 | a {
29 | color:#315479;
30 | }
31 |
32 | .letters {
33 | width:100%;
34 | text-align:center;
35 | margin:0.6em;
36 | padding:0.1em;
37 | border-bottom:1px solid gray;
38 | }
39 |
40 | div.entry {
41 | padding: 0.5em;
42 | background-color: #e1e7ed;
43 | border-radius: 0.2em;
44 | color: #103a51;
45 | margin: 0.5em 0;
46 | }
47 |
48 | .name {
49 | font-family: "Source Code Pro";
50 | font-size: 1.1em;
51 | }
52 |
53 | .occurrences {
54 | margin-left: 1em;
55 | margin-top: 5px;
56 | }
57 |
--------------------------------------------------------------------------------
/doc/lib/remove.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/remove.png
--------------------------------------------------------------------------------
/doc/lib/selected-implicits.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/selected-implicits.png
--------------------------------------------------------------------------------
/doc/lib/selected-right-implicits.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/selected-right-implicits.png
--------------------------------------------------------------------------------
/doc/lib/selected-right.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/selected-right.png
--------------------------------------------------------------------------------
/doc/lib/selected.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/selected.png
--------------------------------------------------------------------------------
/doc/lib/selected2-right.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/selected2-right.png
--------------------------------------------------------------------------------
/doc/lib/selected2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/selected2.png
--------------------------------------------------------------------------------
/doc/lib/signaturebg.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/signaturebg.gif
--------------------------------------------------------------------------------
/doc/lib/signaturebg2.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/signaturebg2.gif
--------------------------------------------------------------------------------
/doc/lib/source-code-pro-v6-latin-700.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/source-code-pro-v6-latin-700.eot
--------------------------------------------------------------------------------
/doc/lib/source-code-pro-v6-latin-700.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/source-code-pro-v6-latin-700.ttf
--------------------------------------------------------------------------------
/doc/lib/source-code-pro-v6-latin-700.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/source-code-pro-v6-latin-700.woff
--------------------------------------------------------------------------------
/doc/lib/source-code-pro-v6-latin-regular.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/source-code-pro-v6-latin-regular.eot
--------------------------------------------------------------------------------
/doc/lib/source-code-pro-v6-latin-regular.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/source-code-pro-v6-latin-regular.ttf
--------------------------------------------------------------------------------
/doc/lib/source-code-pro-v6-latin-regular.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/source-code-pro-v6-latin-regular.woff
--------------------------------------------------------------------------------
/doc/lib/trait.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/trait.png
--------------------------------------------------------------------------------
/doc/lib/trait_big.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/trait_big.png
--------------------------------------------------------------------------------
/doc/lib/trait_diagram.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/trait_diagram.png
--------------------------------------------------------------------------------
/doc/lib/trait_to_object_big.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/trait_to_object_big.png
--------------------------------------------------------------------------------
/doc/lib/type.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/type.png
--------------------------------------------------------------------------------
/doc/lib/type_big.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/type_big.png
--------------------------------------------------------------------------------
/doc/lib/type_diagram.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/type_diagram.png
--------------------------------------------------------------------------------
/doc/lib/type_to_object_big.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/type_to_object_big.png
--------------------------------------------------------------------------------
/doc/lib/typebg.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/typebg.gif
--------------------------------------------------------------------------------
/doc/lib/unselected.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/unselected.png
--------------------------------------------------------------------------------
/doc/lib/valuemembersbg.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MarkCLewis/OOAbstractDataStructScala/97ccafe018f6cdbefff6dcce74157b0bc5038bac/doc/lib/valuemembersbg.gif
--------------------------------------------------------------------------------
/generateDocs.sh:
--------------------------------------------------------------------------------
1 | scaladoc -d doc $(find src/ -name *.scala)
2 |
3 |
--------------------------------------------------------------------------------
/runApp.sh:
--------------------------------------------------------------------------------
1 | scala -cp bin:/home/mlewis/scalafx_2.12.0-M3-8.0.60-R10-SNAPSHOT.jar:/home/mlewis/akka-2.4.7/lib/akka/akka-actor_2.11-2.4.7.jar:/home/mlewis/akka-2.4.7/lib/akka/config-1.3.0.jar:/home/mlewis/workspace/junit-4.12.jar:/home/mlewis/workspace/hamcrest-core-1.3.jar $1
2 |
--------------------------------------------------------------------------------
/src/advscala/Distance.scala:
--------------------------------------------------------------------------------
1 | package advscala
2 |
3 | class Mile(val dist: Double) extends AnyVal {
4 | override def toString = dist+" mile"+(if (dist != 1.0) "s" else "")
5 | def +(m: Mile) = new Mile(dist + m.dist)
6 | def toKilometers = new Kilometer(dist * 1.60934)
7 | }
8 |
9 | class Kilometer(val dist: Double) extends AnyVal {
10 | override def toString = dist+" km"
11 | def +(km: Kilometer) = new Kilometer(dist + km.dist)
12 | def toMiles = new Mile(dist * 0.621371)
13 | }
14 |
15 | object Distance extends App {
16 | val marathon = new Mile(26.2)
17 | val fivek = new Kilometer(5)
18 |
19 | println(marathon + fivek.toMiles)
20 | }
--------------------------------------------------------------------------------
/src/advscala/NestedClasses.scala:
--------------------------------------------------------------------------------
1 | package advscala
2 |
3 | class NestedClasses(x: Double, y: Double) {
4 | val root: Node = new Plus(new Num(x), new Num(y))
5 |
6 | trait Node {
7 | def eval: Double
8 | }
9 |
10 | class Plus(left: Node, right: Node) extends Node {
11 | def eval = left.eval + right.eval
12 | }
13 |
14 | class Num(n: Double) extends Node {
15 | def eval = n
16 | }
17 | }
18 |
19 | object NestedClass {
20 | def main(args: Array[String]) {
21 | val a = new NestedClasses(4, 5)
22 | val b = new NestedClasses(8.7, 9.3)
23 |
24 | a.root match {
25 | case n: a.Num => println("A number")
26 | case n: a.Node => println("Not a number")
27 | }
28 |
29 | def evalNode(n: NestedClasses#Node) = n.eval
30 | def evalNodeA(n: a.Node) = n.eval
31 | def evalNodeB(n: b.Node) = n.eval
32 |
33 | println(evalNode(a.root))
34 | println(evalNodeA(a.root))
35 | // println(evalNodeB(a.root)) // This is a type mismatch.
36 | println(evalNode(b.root))
37 | // println(evalNodeA(b.root)) // This is a type mismatch.
38 | println(evalNodeB(b.root))
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/advscala/Vect2D.scala:
--------------------------------------------------------------------------------
1 | package advscala
2 |
3 | trait Vect2D {
4 | val x: Double
5 | val y: Double
6 | val mag = math.sqrt(x * x + y * y)
7 | }
8 |
9 | object Vect2DTester extends App {
10 | val v = new Vect2D {
11 | val x = 3.0
12 | val y = 4.0
13 | }
14 |
15 | println(v.mag)
16 |
17 | val v2 = new {
18 | val x = 3.0
19 | val y = 4.0
20 | } with Vect2D
21 |
22 | println(v2.mag)
23 |
24 | class Vect2DClass(_x: Double, _y: Double) extends {
25 | val x = _x
26 | val y = _y
27 | } with Vect2D {
28 | // Other stuff we want in the class
29 | }
30 |
31 | val v3 = new Vect2DClass(3,4)
32 |
33 | println(v3.mag)
34 | }
--------------------------------------------------------------------------------
/src/advscala/Vect3D.scala:
--------------------------------------------------------------------------------
1 | package advscala
2 |
3 | class Vect3D(val x: Double, val y: Double, val z: Double) {
4 | def +(v: Vect3D) = Vect3D(x + v.x, y + v.y, z + v.z)
5 | def -(v: Vect3D) = Vect3D(x - v.x, y - v.y, z - v.z)
6 | def *(c: Double) = Vect3D(c * x, c * y, c * z)
7 | def /(c: Double) = Vect3D(c / x, c / y, c / z)
8 | def dot(v: Vect3D) = x * v.x + y * v.y + z * v.z
9 | def cross(v: Vect3D) = Vect3D(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x)
10 | }
11 |
12 | object Vect3D {
13 | def apply(x: Double, y: Double, z: Double) = {
14 | new Vect3D(x, y, z)
15 | }
16 |
17 | def unapply(str: String): Option[(Double, Double, Double)] = {
18 | val s = str.trim
19 | if (!s.startsWith("(") || !s.endsWith(")")) None
20 | else {
21 | val parts = s.substring(1, s.length - 1).split(",")
22 | if (parts.length != 3) None
23 | else try {
24 | Some(parts(0).trim.toDouble, parts(1).trim.toDouble, parts(2).trim.toDouble)
25 | } catch {
26 | case e: NumberFormatException => None
27 | }
28 | }
29 | }
30 |
31 | }
32 |
33 | object TestingApp extends App {
34 | // implicit def doubleToScaling(c: Double): VectScaler = new VectScaler(c)
35 |
36 | implicit class VectScaler(c: Double) {
37 | def *(v: Vect3D): Vect3D = Vect3D(c * v.x, c * v.y, c * v.z)
38 | }
39 |
40 | val v = Vect3D(1, 2, 3)
41 | v * 3
42 | 3 * v
43 |
44 | "(1,4.5,83)" match {
45 | case Vect3D(x, y, z) => println(x+" "+y+" "+z)
46 | }
47 |
48 | import Stream._
49 | def fibFrom(a: BigInt, b: BigInt): Stream[BigInt] = a #:: fibFrom(b, a + b)
50 |
51 | fibFrom(1, 1).take(100).toList
52 |
53 | def structRead[A <: { def hasNextInt(): Boolean; def nextInt(): Int }](source: A): List[Int] = {
54 | var buf = List[Int]()
55 | while (source.hasNextInt) buf ::= source.nextInt
56 | buf.reverse
57 | }
58 |
59 | }
60 |
61 |
--------------------------------------------------------------------------------
/src/binaryfiles/adt/FixedRecordSeq.scala:
--------------------------------------------------------------------------------
1 | package binaryfiles.adt
2 |
3 | import java.io.DataInput
4 | import java.io.DataOutput
5 | import java.io.File
6 | import java.io.RandomAccessFile
7 |
8 | import scala.collection.mutable
9 |
10 | class FixedRecordSeq[A](
11 | file: File,
12 | recordLength: Int,
13 | reader: DataInput => A,
14 | writer: (DataOutput, A) => Unit) extends mutable.IndexedSeq[A] {
15 |
16 | private val raf = new RandomAccessFile(file, "rw")
17 |
18 | def apply(index: Int): A = {
19 | raf.seek(recordLength * index)
20 | reader(raf)
21 | }
22 |
23 | def update(index: Int, a: A): Unit = {
24 | raf.seek(recordLength * index)
25 | writer(raf, a)
26 | }
27 |
28 | def length: Int = (raf.length() / recordLength).toInt
29 |
30 | def close(): Unit = raf.close()
31 | }
--------------------------------------------------------------------------------
/src/binaryfiles/adt/VariableRecordSeq.scala:
--------------------------------------------------------------------------------
1 | package binaryfiles.adt
2 |
3 | import collection.mutable
4 | import java.io._
5 |
6 | class VariableRecordSeq[A](
7 | index: File,
8 | data: File,
9 | reader: DataInput => A,
10 | writer: (DataOutput, A) => Unit) extends mutable.IndexedSeq[A] {
11 |
12 | private val indexFile = new RandomAccessFile(index, "rw")
13 | private val dataFile = new RandomAccessFile(data, "rw")
14 |
15 | def apply(index: Int): A = {
16 | indexFile.seek(12 * index)
17 | val pos = indexFile.readLong()
18 | dataFile.seek(pos)
19 | reader(dataFile)
20 | }
21 |
22 | def update(index: Int, a: A): Unit = {
23 | val baos = new ByteArrayOutputStream()
24 | val dos = new DataOutputStream(baos)
25 | writer(dos, a)
26 | val outData = baos.toByteArray()
27 | val (pos, len) = if (index < length) {
28 | indexFile.seek(12 * index)
29 | val p = indexFile.readLong()
30 | val l = indexFile.readInt()
31 | if (baos.size() <= l) (p, l) else (dataFile.length(), outData.length)
32 | } else (dataFile.length(), outData.length)
33 | dataFile.seek(pos)
34 | dataFile.write(outData)
35 | indexFile.seek(12 * index)
36 | indexFile.writeLong(pos)
37 | indexFile.writeInt(len)
38 | }
39 |
40 | def length: Int = (indexFile.length() / 12).toInt
41 |
42 | def close(): Unit = {
43 | indexFile.close()
44 | dataFile.close()
45 | }
46 | }
--------------------------------------------------------------------------------
/src/guigraphics/FirstGUI.scala:
--------------------------------------------------------------------------------
1 | package guigraphics
2 |
3 | import scalafx.Includes._
4 | import scalafx.application.JFXApp
5 | import scalafx.scene.Scene
6 | import scalafx.scene.control.Button
7 | import scalafx.scene.shape.Ellipse
8 | import scalafx.scene.paint.Color
9 |
10 | object FirstGUI extends JFXApp {
11 | stage = new JFXApp.PrimaryStage {
12 | title = "First GUI"
13 | scene = new Scene(400,200) {
14 | val button = new Button("Click Me")
15 | button.layoutX = 50
16 | button.layoutY = 50
17 | val ellipse = Ellipse(300, 50, 50, 25)
18 | ellipse.fill = Color.Red
19 | content = List(button, ellipse)
20 | }
21 | }
22 | }
--------------------------------------------------------------------------------
/src/guigraphics/KeyboardMouseInput.scala:
--------------------------------------------------------------------------------
1 | package guigraphics
2 |
3 | import scalafx.Includes._
4 | import scalafx.application.JFXApp
5 | import scalafx.scene.Scene
6 | import scalafx.scene.image.ImageView
7 | import scalafx.scene.shape.Rectangle
8 | import scalafx.scene.input.MouseEvent
9 | import scalafx.scene.paint.Color
10 | import scalafx.scene.input.KeyEvent
11 | import scalafx.scene.input.KeyCode
12 |
13 | object KeyboardMouseInput extends JFXApp {
14 | stage = new JFXApp.PrimaryStage {
15 | title = "Keyboard and Mouse Input"
16 | scene = new Scene(600, 600) {
17 | val img = new ImageView("file:Mimas_Cassini.jpg")
18 | val box = Rectangle(0, 0, 30, 30)
19 | box.fill = Color.Green
20 | content = List(img, box)
21 | onMouseMoved = (me: MouseEvent) => {
22 | img.x = me.x
23 | img.y = me.y
24 | }
25 | onKeyPressed = (ke: KeyEvent) => {
26 | ke.code match {
27 | case KeyCode.Up => box.y = box.y.value - 2
28 | case KeyCode.Down => box.y = box.y.value + 2
29 | case KeyCode.Left => box.x = box.x.value - 2
30 | case KeyCode.Right => box.x = box.x.value + 2
31 | case _ =>
32 | }
33 | }
34 | }
35 | }
36 | }
--------------------------------------------------------------------------------
/src/guigraphics/v2/DrawRectangle.scala:
--------------------------------------------------------------------------------
1 | package guigraphics.v2
2 |
3 | import scalafx.Includes._
4 | import scalafx.scene.canvas.GraphicsContext
5 | import scalafx.scene.paint.Color
6 | import scalafx.scene.Node
7 | import scalafx.scene.layout.VBox
8 | import scalafx.scene.control.TextField
9 | import scalafx.scene.control.ColorPicker
10 | import scalafx.event.ActionEvent
11 | import scalafx.scene.layout.Priority
12 |
13 | class DrawRectangle(
14 | d: Drawing,
15 | private var _x: Double,
16 | private var _y: Double,
17 | private var _width: Double,
18 | private var _height: Double,
19 | private var _color: Color) extends Drawable(d) {
20 |
21 | private var propPanel: Option[Node] = None
22 |
23 | override def toString = "Rectangle"
24 |
25 | def draw(gc: GraphicsContext): Unit = {
26 | gc.fill = _color
27 | gc.fillRect(_x, _y, _width, _height)
28 | }
29 |
30 | def propertiesPanel(): Node = {
31 | if (propPanel.isEmpty) {
32 | val panel = new VBox
33 | val xField = DrawingMain.labeledTextField("x", _x.toString, s => { _x = s.toDouble; drawing.draw() })
34 | val yField = DrawingMain.labeledTextField("y", _y.toString, s => { _y = s.toDouble; drawing.draw() })
35 | val widthField = DrawingMain.labeledTextField("width", _width.toString, s => { _width = s.toDouble; drawing.draw() })
36 | val heightField = DrawingMain.labeledTextField("height", _height.toString, s => { _height = s.toDouble; drawing.draw() })
37 | val colorPicker = new ColorPicker(_color)
38 | colorPicker.onAction = (ae: ActionEvent) => {
39 | _color = colorPicker.value.value
40 | drawing.draw()
41 | }
42 | panel.children = List(xField, yField, widthField, heightField, colorPicker)
43 | propPanel = Some(panel)
44 | }
45 | propPanel.get
46 | }
47 | }
--------------------------------------------------------------------------------
/src/guigraphics/v2/DrawText.scala:
--------------------------------------------------------------------------------
1 | package guigraphics.v2
2 |
3 | import scalafx.Includes._
4 | import scalafx.scene.canvas.GraphicsContext
5 | import scalafx.scene.paint.Color
6 | import scalafx.scene.Node
7 | import scalafx.scene.layout.VBox
8 | import scalafx.scene.control.ColorPicker
9 | import scalafx.event.ActionEvent
10 |
11 | class DrawText(
12 | d: Drawing,
13 | private var _x: Double,
14 | private var _y: Double,
15 | private var _text: String,
16 | private var _color: Color) extends Drawable(d) {
17 |
18 | private var propPanel: Option[Node] = None
19 |
20 | override def toString = "Text: "+_text
21 |
22 | def draw(gc: GraphicsContext): Unit = {
23 | gc.fill = _color
24 | gc.fillText(_text, _x, _y)
25 | }
26 |
27 | def propertiesPanel(): Node = {
28 | if (propPanel.isEmpty) {
29 | val panel = new VBox
30 | val textField = DrawingMain.labeledTextField("Text", _text, s => { _text = s; drawing.draw() })
31 | val xField = DrawingMain.labeledTextField("x", _x.toString, s => { _x = s.toDouble; drawing.draw() })
32 | val yField = DrawingMain.labeledTextField("y", _y.toString, s => { _y = s.toDouble; drawing.draw() })
33 | val colorPicker = new ColorPicker(_color)
34 | colorPicker.onAction = (ae: ActionEvent) => {
35 | _color = colorPicker.value.value
36 | drawing.draw()
37 | }
38 | panel.children = List(textField, xField, yField, colorPicker)
39 | propPanel = Some(panel)
40 | }
41 | propPanel.get
42 | }
43 | }
--------------------------------------------------------------------------------
/src/guigraphics/v2/DrawTransform.scala:
--------------------------------------------------------------------------------
1 | package guigraphics.v2
2 |
3 | import scalafx.Includes._
4 | import scalafx.scene.Node
5 | import scalafx.scene.canvas.GraphicsContext
6 | import scalafx.scene.layout.VBox
7 | import scalafx.scene.control.ComboBox
8 | import scalafx.event.ActionEvent
9 | import scalafx.scene.transform.Rotate
10 | import scalafx.scene.transform.Translate
11 | import scalafx.scene.transform.Scale
12 | import scalafx.scene.transform.Shear
13 |
14 | class DrawTransform(d: Drawing) extends Drawable(d) {
15 | private var _children = List[Drawable]()
16 | private var propPanel: Option[Node] = None
17 | private var transformType = DrawTransform.Translate
18 | private var value1 = 0.0
19 | private var value2 = 0.0
20 |
21 | def children = _children
22 |
23 | override def toString = "Transform"
24 |
25 | def addChild(d: Drawable): Unit = {
26 | _children ::= d
27 | }
28 |
29 | def removeChild(d: Drawable): Unit = {
30 | _children = _children.filter(_ != d)
31 | }
32 |
33 | def draw(gc: GraphicsContext): Unit = {
34 | gc.save()
35 | transformType match {
36 | case DrawTransform.Rotate => gc.rotate(value1)
37 | case DrawTransform.Translate => gc.translate(value1, value2)
38 | case DrawTransform.Scale => gc.scale(value1, value2)
39 | case DrawTransform.Shear => gc.transform(1.0, value1, value2, 1.0, 0.0, 0.0)
40 | }
41 | _children.foreach(_.draw(gc))
42 | gc.restore()
43 | }
44 |
45 | def propertiesPanel(): Node = {
46 | if (propPanel.isEmpty) {
47 | val panel = new VBox
48 | val combo = new ComboBox(DrawTransform.values.toSeq)
49 | combo.onAction = (ae: ActionEvent) => {
50 | transformType = combo.selectionModel.value.selectedItem.value
51 | drawing.draw()
52 | }
53 | combo.selectionModel.value.select(transformType)
54 | val v1Field = DrawingMain.labeledTextField("x/theta", value1.toString, s => { value1 = s.toDouble; drawing.draw() })
55 | val v2Field = DrawingMain.labeledTextField("y", value2.toString, s => { value2 = s.toDouble; drawing.draw() })
56 | panel.children = List(combo, v1Field, v2Field)
57 | propPanel = Some(panel)
58 | }
59 | propPanel.get
60 | }
61 | }
62 |
63 | object DrawTransform extends Enumeration {
64 | val Rotate, Scale, Shear, Translate = Value
65 | }
--------------------------------------------------------------------------------
/src/guigraphics/v2/Drawable.scala:
--------------------------------------------------------------------------------
1 | package guigraphics.v2
2 |
3 | import scalafx.scene.canvas.GraphicsContext
4 | import scalafx.scene.Node
5 |
6 | abstract class Drawable(val drawing: Drawing) {
7 | def draw(gc: GraphicsContext): Unit
8 | def propertiesPanel(): Node
9 | }
--------------------------------------------------------------------------------
/src/guigraphics/v2/Drawing.scala:
--------------------------------------------------------------------------------
1 | package guigraphics.v2
2 |
3 | import scalafx.scene.canvas.GraphicsContext
4 | import scalafx.scene.control.TreeItem
5 | import scalafx.scene.paint.Color
6 |
7 | class Drawing(private var gc: GraphicsContext) {
8 | private var root = new DrawTransform(this)
9 |
10 | def draw(): Unit = {
11 | gc.fill = Color.White
12 | gc.fillRect(0, 0, 2000, 2000)
13 | root.draw(gc)
14 | }
15 |
16 | def makeTree: TreeItem[Drawable] = {
17 | def helper(d: Drawable): TreeItem[Drawable] = d match {
18 | case dt: DrawTransform =>
19 | val item = new TreeItem(d)
20 | item.children = dt.children.map(c => helper(c))
21 | item
22 | case _ => new TreeItem(d)
23 | }
24 | helper(root)
25 | }
26 | }
--------------------------------------------------------------------------------
/src/hashtables/adt/HashMethods.scala:
--------------------------------------------------------------------------------
1 | package hashtables.adt
2 |
3 | object HashingMethods extends Enumeration {
4 | val Division, Multiplication = Value
5 |
6 | private[adt] def buildHashFunction[K](method: Value): (K, Int) => Int = method match {
7 | case Division => (key, size) => key.hashCode().abs % size
8 | case Multiplication => (key, size) => {
9 | val x = key.hashCode() * A
10 | (size * (x - x.toInt).abs).toInt
11 | }
12 | }
13 |
14 | val A = (math.sqrt(5) - 1) / 2
15 | }
16 |
17 | object ProbingMethods extends Enumeration {
18 | val Linear, Quadratic = Value
19 |
20 | private[adt] def buildProbingFunction(method: Value): (Int, Int, Int) => Int = method match {
21 | case Linear => (i, j, size) => (i + j) % size
22 | case Quadratic => (i, j, size) => (i + 2 * j + 3 * j * j) % size
23 | }
24 | }
--------------------------------------------------------------------------------
/src/hashtables/adt/TestHashingOrder.scala:
--------------------------------------------------------------------------------
1 | package hashtables.adt
2 |
3 | object TestHashingOrder extends App {
4 | val chm = ChainingHashMap[Double, Double](HashingMethods.Division)
5 | for (i <- 1 to 1000000) chm += math.random -> math.random
6 | println(chm.maxBin)
7 | }
8 |
--------------------------------------------------------------------------------
/src/heaps/adt/BinaryHeapPriorityQueue.scala:
--------------------------------------------------------------------------------
1 | package heaps.adt
2 |
3 | import scala.reflect.ClassTag
4 |
5 | import priorityqueues.adt.PriorityQueue
6 |
7 | class BinaryHeapPriorityQueue[A: ClassTag](comp: (A, A) => Int) extends PriorityQueue[A] {
8 | private var heap = new Array[A](10)
9 | private var end = 1
10 |
11 | def enqueue(obj: A): Unit = {
12 | if (end >= heap.length) {
13 | val tmp = new Array[A](heap.length * 2)
14 | Array.copy(heap, 0, tmp, 0, heap.length)
15 | heap = tmp
16 | }
17 | var bubble = end
18 | while (bubble > 1 && comp(obj, heap(bubble / 2)) > 0) {
19 | heap(bubble) = heap(bubble / 2)
20 | bubble /= 2
21 | }
22 | heap(bubble) = obj
23 | end += 1
24 | }
25 |
26 | def dequeue(): A = {
27 | val ret = heap(1)
28 | end -= 1
29 | val temp = heap(end)
30 | heap(end) = heap(0) // Clear reference to temp
31 | var stone = 1
32 | var flag = true
33 | while (flag && stone * 2 < end) {
34 | var greaterChild = if (stone * 2 + 1 < end && comp(heap(stone * 2 + 1), heap(stone * 2)) > 0)
35 | stone * 2 + 1 else stone * 2
36 | if (comp(heap(greaterChild), temp) > 0) {
37 | heap(stone) = heap(greaterChild)
38 | stone = greaterChild
39 | } else {
40 | flag = false
41 | }
42 | }
43 | heap(stone) = temp
44 | ret
45 | }
46 |
47 | def peek: A = heap(1)
48 |
49 | def isEmpty: Boolean = end == 1
50 | }
--------------------------------------------------------------------------------
/src/heaps/util/Sorts.scala:
--------------------------------------------------------------------------------
1 | package heaps.util
2 |
3 | object Sorts extends App {
4 | def heapsort[A](a: Array[A])(comp: (A, A) => Int): Unit = {
5 | for (end <- 1 until a.length) {
6 | val tmp = a(end)
7 | var bubble = end
8 | while (bubble > 0 && comp(tmp, a((bubble + 1) / 2 - 1)) > 0) {
9 | a(bubble) = a((bubble + 1) / 2 - 1)
10 | bubble = (bubble + 1) / 2 - 1
11 | }
12 | a(bubble) = tmp
13 | }
14 | for (end <- a.length - 1 until 0 by -1) {
15 | val tmp = a(end)
16 | a(end) = a(0)
17 | var stone = 0
18 | var flag = true
19 | while (flag && (stone + 1) * 2 - 1 < end) {
20 | val greaterChild = if ((stone + 1) * 2 < end && comp(a((stone + 1) * 2), a((stone + 1) * 2 - 1)) > 0)
21 | (stone + 1) * 2 else (stone + 1) * 2 - 1
22 | if (comp(a(greaterChild), tmp) > 0) {
23 | a(stone) = a(greaterChild)
24 | stone = greaterChild
25 | } else {
26 | flag = false
27 | }
28 | }
29 | a(stone) = tmp
30 | }
31 | }
32 |
33 | val arr = Array.fill(10)(math.random)
34 | heapsort(arr)(_.compareTo(_))
35 | arr.foreach(println)
36 | }
--------------------------------------------------------------------------------
/src/iostreams/ByteCopy.scala:
--------------------------------------------------------------------------------
1 | package iostreams
2 |
3 | import java.io.FileInputStream
4 | import java.io.FileOutputStream
5 |
6 | object ByteCopy extends App {
7 | val fis = new FileInputStream(args(0))
8 | val fos = new FileOutputStream(args(1))
9 | var byte = fis.read()
10 | while (byte >= 0) {
11 | fos.write(byte)
12 | byte = fis.read()
13 | }
14 | fis.close()
15 | fos.close()
16 | }
--------------------------------------------------------------------------------
/src/iostreams/LoanPattern.scala:
--------------------------------------------------------------------------------
1 | package iostreams
2 |
3 | import java.io.IOException
4 | import java.io.FileInputStream
5 | import java.io.FileNotFoundException
6 |
7 | object LoanPattern extends App {
8 | def useFileInputStream[A](fileName: String)(body: FileInputStream => A): A = {
9 | val fis = new FileInputStream(fileName)
10 | try {
11 | body(fis)
12 | } finally {
13 | fis.close()
14 | }
15 | }
16 |
17 | try {
18 | useFileInputStream(args(0))(fis => {
19 | var byte = fis.read()
20 | while (byte >= 0) {
21 | print(byte+" ")
22 | byte = fis.read()
23 | }
24 | println()
25 | })
26 | } catch {
27 | case ex: FileNotFoundException =>
28 | println("The file "+args(0)+" could not be opened.")
29 | case ex: IOException =>
30 | println("There was a problem working with the file.")
31 | }
32 | }
--------------------------------------------------------------------------------
/src/iostreams/ReadBytes.scala:
--------------------------------------------------------------------------------
1 | package iostreams
2 |
3 | import java.io.FileInputStream
4 |
5 | object ReadBytes extends App {
6 | val fis = new FileInputStream(args(0))
7 | var byte = fis.read()
8 | while (byte >= 0) {
9 | print(byte+" ")
10 | byte = fis.read()
11 | }
12 | println()
13 | fis.close()
14 | }
--------------------------------------------------------------------------------
/src/iostreams/ReadBytesTry.scala:
--------------------------------------------------------------------------------
1 | package iostreams
2 |
3 | import java.io.IOException
4 | import java.io.FileInputStream
5 | import java.io.FileNotFoundException
6 |
7 | object ReadBytesTry extends App {
8 | try {
9 | val fis = new FileInputStream(args(0))
10 | var byte = fis.read()
11 | while (byte >= 0) {
12 | print(byte+" ")
13 | byte = fis.read()
14 | }
15 | println()
16 | fis.close()
17 | } catch {
18 | case ex: FileNotFoundException =>
19 | println("The file "+args(0)+" could not be opened.")
20 | case ex: IOException =>
21 | println("There was a problem working with the file.")
22 | }
23 | }
--------------------------------------------------------------------------------
/src/iostreams/ReadBytesTryFinally.scala:
--------------------------------------------------------------------------------
1 | package iostreams
2 |
3 | import java.io.IOException
4 | import java.io.FileInputStream
5 | import java.io.FileNotFoundException
6 |
7 | object ReadBytesTryFinally extends App {
8 | try {
9 | val fis = new FileInputStream(args(0))
10 | try {
11 | var byte = fis.read()
12 | while (byte >= 0) {
13 | print(byte+" ")
14 | byte = fis.read()
15 | }
16 | println()
17 | } catch {
18 | case ex: IOException =>
19 | println("There was a problem working with the file.")
20 | } finally {
21 | fis.close()
22 | }
23 | } catch {
24 | case ex: FileNotFoundException =>
25 | println("The file "+args(0)+" could not be opened.")
26 | }
27 | }
--------------------------------------------------------------------------------
/src/iostreams/ReadWriteBinary.scala:
--------------------------------------------------------------------------------
1 | package iostreams
2 |
3 | import java.io.FileInputStream
4 | import java.io.FileOutputStream
5 | import java.io.BufferedInputStream
6 | import java.io.BufferedOutputStream
7 | import java.io.DataInputStream
8 | import java.io.DataOutputStream
9 |
10 | object ReadWriteBinary {
11 | def withDOS[A](fileName: String)(body: DataOutputStream => A): A = {
12 | val dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)))
13 | try {
14 | body(dos)
15 | } finally {
16 | dos.close()
17 | }
18 | }
19 |
20 | def withDIS[A](fileName: String)(body: DataInputStream => A): A = {
21 | val dis = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName)))
22 | try {
23 | body(dis)
24 | } finally {
25 | dis.close()
26 | }
27 | }
28 |
29 | def writeDoubleArray(fileName: String, data: Array[Double]): Unit = {
30 | withDOS(fileName)(dos => {
31 | dos.writeInt(data.size)
32 | data.foreach(x => dos.writeDouble(x))
33 | })
34 | }
35 |
36 | def readDoubleArray(fileName: String): Array[Double] = {
37 | withDIS(fileName)(dis => {
38 | Array.fill(dis.readInt)(dis.readDouble)
39 | })
40 | }
41 | }
--------------------------------------------------------------------------------
/src/iostreams/SerializationTest.scala:
--------------------------------------------------------------------------------
1 | package iostreams
2 |
3 | import java.io.FileInputStream
4 | import java.io.FileOutputStream
5 | import java.io.ObjectInputStream
6 | import java.io.BufferedInputStream
7 | import java.io.ObjectOutputStream
8 | import java.io.BufferedOutputStream
9 |
10 | class Student(val name: String, val grades: Array[Int]) extends Serializable
11 |
12 | object SerializationTest extends App {
13 | args(0) match {
14 | case "-r" =>
15 | val ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(args(1))))
16 | ois.readObject() match {
17 | case s: Student => println(s.name+" "+s.grades.mkString(", "))
18 | case _ => println("Unidentified type.")
19 | }
20 | ois.close()
21 | case "-w" =>
22 | val oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(args(1))))
23 | val s = new Student(args(2), args.drop(3).map(_.toInt))
24 | oos.writeObject(s)
25 | oos.close()
26 | case _ =>
27 | println("Usage: -r filename | -w filename name g1 g2 ...")
28 | }
29 | }
--------------------------------------------------------------------------------
/src/iostreams/XMLCode.scala:
--------------------------------------------------------------------------------
1 | package iostreams
2 |
3 | object XMLCode extends App {
4 | val drawXML =
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 | This is the text that is drawn.
13 |
14 |
15 |
16 |
17 | val name = "Ginny"
18 | val age = 16
19 | val description = "Red hair and second hand textbooks."
20 | val xmlRecord = {description}
21 |
22 | val costs = List(8,5,6,9,10)
23 | val costXML = {costs.map(c => {c})}
24 |
25 | drawXML \ "drawable"
26 | drawXML \ "@x"
27 | drawXML \\ "@x"
28 | drawXML \ "drawable" \ "drawable"
29 | (drawXML \ "drawable" \ "drawable")(0) \ "@x"
30 | (drawXML \ "drawable" \ "drawable").filter(n => (n \ "@type").text=="rectangle") \ "@x"
31 | (drawXML \ "drawable" \ "drawable").map(n => ((n \ "@x").text, (n \ "@y").text, (n \ "@type").text))
32 | }
--------------------------------------------------------------------------------
/src/iostreams/drawing/Commands.scala:
--------------------------------------------------------------------------------
1 | package iostreams.drawing
2 |
3 | import stackqueue.util.RPNCalc
4 | import scalafx.application.Platform
5 |
6 | object Commands {
7 | private val commands = Map[String, (String, Drawing) => Any](
8 | "add" -> ((rest, d) => rest.trim.split(" +").map(_.toInt).sum),
9 | "echo" -> ((rest, d) => rest.trim),
10 | "refresh" -> ((rest, d) => Platform.runLater { d.draw() } ),
11 | "rpn" -> ((rest,d) => (RPNCalc(rest.trim.split(" +"), d.vars))),
12 | "set" -> ((rest,d) => {
13 | val parts = rest.trim.split(" +")
14 | d.vars(parts(0)) = parts(1).toDouble
15 | parts(0)+" = "+parts(1)
16 | }),
17 | "freeze" -> ((rest,d) => Thread.sleep(rest.trim.toInt*1000)))
18 |
19 | def apply(input: String, drawing: Drawing): Any = {
20 | val spaceIndex = input.indexOf(' ')
21 | val (command, rest) = if (spaceIndex < 0) (input.toLowerCase(), "")
22 | else (input.take(spaceIndex).toLowerCase(), input.drop(spaceIndex))
23 | if (commands.contains(command)) commands(command)(rest, drawing) else "Not a valid command."
24 | }
25 | }
--------------------------------------------------------------------------------
/src/iostreams/drawing/Drawable.scala:
--------------------------------------------------------------------------------
1 | package iostreams.drawing
2 |
3 | import scalafx.scene.canvas.GraphicsContext
4 | import scalafx.scene.Node
5 |
6 | abstract class Drawable(val drawing: Drawing) extends Serializable {
7 | def draw(gc: GraphicsContext): Unit
8 | def propertiesPanel(): Node
9 | def toXML: xml.Node
10 | }
11 |
12 | object Drawable {
13 | def makeDrawable(n: xml.Node, d: Drawing): Drawable = {
14 | (n \ "@type").text match {
15 | case "rectangle" => DrawRectangle(n, d)
16 | case "text" => DrawText(n, d)
17 | case "transform" => DrawTransform(n, d)
18 | case "maze" => DrawMaze(n, d)
19 | case "mandelbrot" => DrawMandelbrot(n, d)
20 | case "julia" => DrawJulia(n, d)
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/src/iostreams/drawing/Drawing.scala:
--------------------------------------------------------------------------------
1 | package iostreams.drawing
2 |
3 | import collection.mutable
4 | import scalafx.scene.canvas.GraphicsContext
5 | import scalafx.scene.control.TreeItem
6 | import scalafx.scene.paint.Color
7 |
8 | class Drawing(private[drawing] val vars:mutable.Map[String, Double]) extends Serializable {
9 | private var root = DrawTransform(this)
10 | @transient private var gc: GraphicsContext = null
11 |
12 | def graphicsContext_=(g: GraphicsContext): Unit = {
13 | gc = g
14 | }
15 |
16 | def graphicsContext = gc
17 |
18 | def draw(): Unit = {
19 | gc.fill = Color.White
20 | gc.fillRect(0, 0, 2000, 2000)
21 | root.draw(gc)
22 | }
23 |
24 | def makeTree: TreeItem[Drawable] = {
25 | def helper(d: Drawable): TreeItem[Drawable] = d match {
26 | case dt: DrawTransform =>
27 | val item = new TreeItem(d)
28 | item.children = dt.children.map(c => helper(c))
29 | item
30 | case _ => new TreeItem(d)
31 | }
32 | helper(root)
33 | }
34 |
35 | def toXML: xml.Node = {
36 |
37 | {root.toXML}
38 | {for((k,v) <- vars) yield }
39 |
40 | }
41 | }
42 |
43 | object Drawing {
44 | def apply(): Drawing = {
45 | new Drawing(mutable.Map())
46 | }
47 |
48 | def apply(n: xml.Node): Drawing = {
49 | val vars = mutable.Map((n \ "var").map(vnode => (vnode \ "@key").text -> (vnode \ "@value").text.toDouble):_*)
50 | val drawing = new Drawing(vars)
51 | drawing.root = DrawTransform(n \ "drawable", drawing)
52 | drawing
53 | }
54 |
55 | def colorToXML(color: Color): xml.Node = {
56 |
57 | }
58 |
59 | def xmlToColor(n: xml.NodeSeq): Color = {
60 | Color((n \ "@red").text.toDouble,(n \ "@green").text.toDouble,(n \ "@blue").text.toDouble,(n \ "@opacity").text.toDouble)
61 | }
62 | }
--------------------------------------------------------------------------------
/src/linkedlist/adt/ImmutableSLList.scala:
--------------------------------------------------------------------------------
1 | package linkedlist.adt
2 |
3 | import collection.immutable.LinearSeq
4 |
5 | sealed abstract class ImmutableSLList[+A] extends LinearSeq[A] {
6 | def ::[B >: A](elem: B): ImmutableSLList[B] = new Cons(elem, this)
7 |
8 | override def iterator = new Iterator[A] {
9 | var rover: LinearSeq[A] = ImmutableSLList.this
10 | def hasNext = !rover.isEmpty
11 | def next: A = {
12 | val ret = rover.head
13 | rover = rover.tail
14 | ret
15 | }
16 | }
17 | }
18 |
19 | final class Cons[A](hd: A, tl: ImmutableSLList[A]) extends ImmutableSLList[A] {
20 | def length = 1 + tl.length
21 | def apply(index: Int): A = if (index == 0) hd else tl.apply(index - 1)
22 | override def isEmpty = false
23 | override def head = hd
24 | override def tail = tl
25 | }
26 |
27 | object MyNil extends ImmutableSLList[Nothing] {
28 | def length = 0
29 | def apply(index: Int) = throw new IllegalArgumentException("Nil has no contents.")
30 | override def isEmpty = true
31 | override def head = throw new IllegalArgumentException("Nil has no head.")
32 | override def tail = throw new IllegalArgumentException("Nil has no tail.")
33 | }
34 |
35 | object ImmutableSLList {
36 | def apply[A](data: A*): ImmutableSLList[A] = {
37 | var ret: ImmutableSLList[A] = MyNil
38 | for (d <- data.reverse) {
39 | ret = new Cons(d, ret)
40 | }
41 | ret
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/linkedlist/adt/ListQueue.scala:
--------------------------------------------------------------------------------
1 | package linkedlist.adt
2 |
3 | class ListQueue[A] extends Queue[A] {
4 | private class Node(val data: A, var next: Node)
5 | private var front: Node = null
6 | private var back: Node = null
7 |
8 | def enqueue(obj: A): Unit = {
9 | if (front == null) {
10 | front = new Node(obj, null)
11 | back = front
12 | } else {
13 | back.next = new Node(obj, null)
14 | back = back.next
15 | }
16 | }
17 |
18 | def dequeue(): A = {
19 | assert(!isEmpty, "Dequeue called on an empty queue.")
20 | val ret = front.data
21 | front = front.next
22 | if (front == null) back = null
23 | ret
24 | }
25 |
26 | def peek: A = front.data
27 |
28 | def isEmpty: Boolean = front == null
29 | }
--------------------------------------------------------------------------------
/src/linkedlist/adt/ListStack.scala:
--------------------------------------------------------------------------------
1 | package linkedlist.adt
2 |
3 | class ListStack[A] extends Stack[A] {
4 | private case class Node(data: A, next: Node)
5 | private var top: Node = null
6 |
7 | def push(obj: A): Unit = {
8 | top = Node(obj, top)
9 | }
10 |
11 | def pop(): A = {
12 | assert(!isEmpty, "Pop called on an empty stack.")
13 | val ret = top.data
14 | top = top.next
15 | ret
16 | }
17 |
18 | def peek: A = top.data
19 |
20 | def isEmpty: Boolean = top == null
21 | }
--------------------------------------------------------------------------------
/src/linkedlist/adt/Queue.scala:
--------------------------------------------------------------------------------
1 | package linkedlist.adt
2 |
3 | /**
4 | * This trait defines a mutable Queue ADT.
5 | * @tparam A the type of data stored
6 | */
7 | trait Queue[A] {
8 | /**
9 | * Add an item to the queue.
10 | * @param obj the item to add
11 | */
12 | def enqueue(obj:A)
13 |
14 | /**
15 | * Remove the item that has been on the longest.
16 | * @return the item that was removed
17 | */
18 | def dequeue():A
19 |
20 | /**
21 | * Return the item that has been on the longest without removing it.
22 | * @return the most recently added item
23 | */
24 | def peek:A
25 |
26 | /**
27 | * Tells whether this queue is empty.
28 | * @return true if there are no items on the queue, otherwise false.
29 | */
30 | def isEmpty:Boolean
31 | }
--------------------------------------------------------------------------------
/src/linkedlist/adt/Stack.scala:
--------------------------------------------------------------------------------
1 | package linkedlist.adt
2 |
3 | /**
4 | * This trait defines a mutable Stack ADT.
5 | * @tparam A the type of data stored
6 | */
7 | trait Stack[A] {
8 | /**
9 | * Add an item to the stack.
10 | * @param obj the item to add
11 | */
12 | def push(obj:A)
13 |
14 | /**
15 | * Remove the most recently added item.
16 | * @return the item that was removed
17 | */
18 | def pop():A
19 |
20 | /**
21 | * Return the most recently added item without removing it.
22 | * @return the most recently added item
23 | */
24 | def peek:A
25 |
26 | /**
27 | * Tells whether this stack is empty.
28 | * @return true if there are no items on the stack, otherwise false.
29 | */
30 | def isEmpty:Boolean
31 | }
--------------------------------------------------------------------------------
/src/mapset/SimpleCode.scala:
--------------------------------------------------------------------------------
1 | package mapset
2 |
3 | import collection.mutable
4 |
5 | object SimpleCode extends App {
6 | def uniqueWords(fileName: String): Set[String] = {
7 | val source = io.Source.fromFile(fileName)
8 | val words = source.getLines.toSeq.flatMap(_.split(" +")).
9 | map(_.filter(_.isLetter).toLowerCase).toSet
10 | source.close()
11 | words
12 | }
13 |
14 | def wordCount(fileName: String): mutable.Map[String, Int] = {
15 | val source = io.Source.fromFile(fileName)
16 | val words = source.getLines.toSeq.flatMap(_.split(" +")).
17 | map(_.filter(_.isLetter).toLowerCase)
18 | val counts = mutable.Map[String, Int]()
19 | for (w <- words) {
20 | if (counts.contains(w)) counts += w -> (counts(w) + 1)
21 | else counts += w -> 1
22 | }
23 | source.close()
24 | counts
25 | }
26 |
27 | def wordCount2(fileName: String): Map[String, Int] = {
28 | val source = io.Source.fromFile(fileName)
29 | val words = source.getLines.toSeq.flatMap(_.split(" +")).
30 | map(_.filter(_.isLetter).toLowerCase)
31 | val counts = words.foldLeft(Map[String, Int]())((m, w) => {
32 | if (m.contains(w)) m + (w -> (m(w) + 1))
33 | else m + (w -> 1)
34 | })
35 | source.close()
36 | counts
37 | }
38 |
39 | def wordCount3(fileName: String): Map[String, Int] = {
40 | val source = io.Source.fromFile(fileName)
41 | val counts = source.getLines.toSeq.flatMap(_.split(" +")).
42 | map(_.filter(_.isLetter).toLowerCase).
43 | foldLeft(Map[String, Int]())((m, w) =>
44 | if (m.contains(w)) m + (w -> (m(w) + 1))
45 | else m + (w -> 1))
46 | source.close()
47 | counts
48 | }
49 |
50 | val nums = Array.tabulate(30)(i => 2*i)
51 | val everyThird = (nums.indices by 3).map(nums)
52 |
53 | }
--------------------------------------------------------------------------------
/src/mapset/drawing/Commands.scala:
--------------------------------------------------------------------------------
1 | package mapset.drawing
2 |
3 | object Commands {
4 | private val commands = Map[String, (String, Drawing) => Any](
5 | "add" -> ((rest, d) => rest.trim.split(" +").map(_.toInt).sum),
6 | "echo" -> ((rest, d) => rest.trim),
7 | "refresh" -> ((rest, d) => d.draw()))
8 |
9 | def apply(input: String, drawing: Drawing): Any = {
10 | val spaceIndex = input.indexOf(' ')
11 | val (command, rest) = if (spaceIndex < 0) (input.toLowerCase(), "")
12 | else (input.take(spaceIndex).toLowerCase(), input.drop(spaceIndex))
13 | if (commands.contains(command)) commands(command)(rest, drawing) else "Not a valid command."
14 | }
15 | }
--------------------------------------------------------------------------------
/src/mapset/drawing/DrawRectangle.scala:
--------------------------------------------------------------------------------
1 | package mapset.drawing
2 |
3 | import scalafx.Includes._
4 | import scalafx.scene.canvas.GraphicsContext
5 | import scalafx.scene.paint.Color
6 | import scalafx.scene.Node
7 | import scalafx.scene.layout.VBox
8 | import scalafx.scene.control.TextField
9 | import scalafx.scene.control.ColorPicker
10 | import scalafx.event.ActionEvent
11 | import scalafx.scene.layout.Priority
12 |
13 | class DrawRectangle(
14 | d: Drawing,
15 | private var _x: Double,
16 | private var _y: Double,
17 | private var _width: Double,
18 | private var _height: Double,
19 | private var _color: Color) extends Drawable(d) {
20 |
21 | private var propPanel: Option[Node] = None
22 |
23 | override def toString = "Rectangle"
24 |
25 | def draw(gc: GraphicsContext): Unit = {
26 | gc.fill = _color
27 | gc.fillRect(_x, _y, _width, _height)
28 | }
29 |
30 | def propertiesPanel(): Node = {
31 | if (propPanel.isEmpty) {
32 | val panel = new VBox
33 | val xField = DrawingMain.labeledTextField("x", _x.toString, s => { _x = s.toDouble; drawing.draw() })
34 | val yField = DrawingMain.labeledTextField("y", _y.toString, s => { _y = s.toDouble; drawing.draw() })
35 | val widthField = DrawingMain.labeledTextField("width", _width.toString, s => { _width = s.toDouble; drawing.draw() })
36 | val heightField = DrawingMain.labeledTextField("height", _height.toString, s => { _height = s.toDouble; drawing.draw() })
37 | val colorPicker = new ColorPicker(_color)
38 | colorPicker.onAction = (ae: ActionEvent) => {
39 | _color = colorPicker.value.value
40 | drawing.draw()
41 | }
42 | panel.children = List(xField, yField, widthField, heightField, colorPicker)
43 | propPanel = Some(panel)
44 | }
45 | propPanel.get
46 | }
47 | }
--------------------------------------------------------------------------------
/src/mapset/drawing/DrawText.scala:
--------------------------------------------------------------------------------
1 | package mapset.drawing
2 |
3 | import scalafx.Includes._
4 | import scalafx.scene.canvas.GraphicsContext
5 | import scalafx.scene.paint.Color
6 | import scalafx.scene.Node
7 | import scalafx.scene.layout.VBox
8 | import scalafx.scene.control.ColorPicker
9 | import scalafx.event.ActionEvent
10 |
11 | class DrawText(
12 | d: Drawing,
13 | private var _x: Double,
14 | private var _y: Double,
15 | private var _text: String,
16 | private var _color: Color) extends Drawable(d) {
17 |
18 | private var propPanel: Option[Node] = None
19 |
20 | override def toString = "Text: "+_text
21 |
22 | def draw(gc: GraphicsContext): Unit = {
23 | gc.fill = _color
24 | gc.fillText(_text, _x, _y)
25 | }
26 |
27 | def propertiesPanel(): Node = {
28 | if (propPanel.isEmpty) {
29 | val panel = new VBox
30 | val textField = DrawingMain.labeledTextField("Text", _text, s => { _text = s; drawing.draw() })
31 | val xField = DrawingMain.labeledTextField("x", _x.toString, s => { _x = s.toDouble; drawing.draw() })
32 | val yField = DrawingMain.labeledTextField("y", _y.toString, s => { _y = s.toDouble; drawing.draw() })
33 | val colorPicker = new ColorPicker(_color)
34 | colorPicker.onAction = (ae: ActionEvent) => {
35 | _color = colorPicker.value.value
36 | drawing.draw()
37 | }
38 | panel.children = List(textField, xField, yField, colorPicker)
39 | propPanel = Some(panel)
40 | }
41 | propPanel.get
42 | }
43 | }
--------------------------------------------------------------------------------
/src/mapset/drawing/DrawTransform.scala:
--------------------------------------------------------------------------------
1 | package mapset.drawing
2 |
3 | import collection.mutable
4 | import scalafx.Includes._
5 | import scalafx.scene.Node
6 | import scalafx.scene.canvas.GraphicsContext
7 | import scalafx.scene.layout.VBox
8 | import scalafx.scene.control.ComboBox
9 | import scalafx.event.ActionEvent
10 | import scalafx.scene.transform.Rotate
11 | import scalafx.scene.transform.Translate
12 | import scalafx.scene.transform.Scale
13 | import scalafx.scene.transform.Shear
14 |
15 | class DrawTransform(d: Drawing) extends Drawable(d) {
16 | private val _children = mutable.Buffer[Drawable]()
17 | private var propPanel: Option[Node] = None
18 | private var transformType = DrawTransform.Translate
19 | private var value1 = 0.0
20 | private var value2 = 0.0
21 |
22 | def children = _children
23 |
24 | override def toString = "Transform"
25 |
26 | def addChild(d: Drawable): Unit = {
27 | _children += d
28 | }
29 |
30 | def removeChild(d: Drawable): Unit = {
31 | _children -= d
32 | }
33 |
34 | def draw(gc: GraphicsContext): Unit = {
35 | gc.save()
36 | transformType match {
37 | case DrawTransform.Rotate => gc.rotate(value1)
38 | case DrawTransform.Translate => gc.translate(value1, value2)
39 | case DrawTransform.Scale => gc.scale(value1, value2)
40 | case DrawTransform.Shear => gc.transform(1.0, value1, value2, 1.0, 0.0, 0.0)
41 | }
42 | _children.foreach(_.draw(gc))
43 | gc.restore()
44 | }
45 |
46 | def propertiesPanel(): Node = {
47 | if (propPanel.isEmpty) {
48 | val panel = new VBox
49 | val combo = new ComboBox(DrawTransform.values.toSeq)
50 | combo.onAction = (ae: ActionEvent) => {
51 | transformType = combo.selectionModel.value.selectedItem.value
52 | drawing.draw()
53 | }
54 | combo.selectionModel.value.select(transformType)
55 | val v1Field = DrawingMain.labeledTextField("x/theta", value1.toString, s => { value1 = s.toDouble; drawing.draw() })
56 | val v2Field = DrawingMain.labeledTextField("y", value2.toString, s => { value2 = s.toDouble; drawing.draw() })
57 | panel.children = List(combo, v1Field, v2Field)
58 | propPanel = Some(panel)
59 | }
60 | propPanel.get
61 | }
62 | }
63 |
64 | object DrawTransform extends Enumeration {
65 | val Rotate, Scale, Shear, Translate = Value
66 | }
--------------------------------------------------------------------------------
/src/mapset/drawing/Drawable.scala:
--------------------------------------------------------------------------------
1 | package mapset.drawing
2 |
3 | import scalafx.scene.canvas.GraphicsContext
4 | import scalafx.scene.Node
5 |
6 | abstract class Drawable(val drawing: Drawing) {
7 | def draw(gc: GraphicsContext): Unit
8 | def propertiesPanel(): Node
9 | }
--------------------------------------------------------------------------------
/src/mapset/drawing/Drawing.scala:
--------------------------------------------------------------------------------
1 | package mapset.drawing
2 |
3 | import scalafx.scene.canvas.GraphicsContext
4 | import scalafx.scene.control.TreeItem
5 | import scalafx.scene.paint.Color
6 |
7 | class Drawing(private var gc: GraphicsContext) {
8 | private var root = new DrawTransform(this)
9 |
10 | def draw(): Unit = {
11 | gc.fill = Color.White
12 | gc.fillRect(0, 0, 2000, 2000)
13 | root.draw(gc)
14 | }
15 |
16 | def makeTree: TreeItem[Drawable] = {
17 | def helper(d: Drawable): TreeItem[Drawable] = d match {
18 | case dt: DrawTransform =>
19 | val item = new TreeItem(d)
20 | item.children = dt.children.map(c => helper(c))
21 | item
22 | case _ => new TreeItem(d)
23 | }
24 | helper(root)
25 | }
26 | }
--------------------------------------------------------------------------------
/src/moretrees/adt/RayTracing.scala:
--------------------------------------------------------------------------------
1 | package moretrees.adt
2 |
3 | object RayTracing extends App {
4 | case class Ray(p0: Array[Double], d: Array[Double]) extends IntersectionOctree.ParamCalc[Sphere] {
5 | def apply(s: Sphere): Double = {
6 | val dist = (p0 zip s.c).map(t => t._1 - t._2)
7 | val a = d(0) * d(0) + d(1) * d(1) + d(2) * d(2)
8 | val b = 2 * (d(0) * dist(0) + d(1) * dist(1) + d(2) * dist(2))
9 | val c = (dist(0) * dist(0) + dist(1) * dist(1) + dist(2) * dist(2)) - s.rad * s.rad
10 | val root = b * b - 4 * a * c
11 | if (root < 0) Double.PositiveInfinity
12 | else (-b - math.sqrt(root)) / (2 * a)
13 | }
14 |
15 | def apply(min: Array[Double], max: Array[Double]): Double = {
16 | if ((p0, min, max).zipped.forall((p, l, h) => p >= l && p <= h)) 0.0 else {
17 | val minp = (0 to 2).map(i => (min(i) - p0(i)) / d(i))
18 | val maxp = (0 to 2).map(i => (max(i) - p0(i)) / d(i))
19 | var ret = Double.PositiveInfinity
20 | for (i <- 0 to 2) {
21 | val first = minp(i) min maxp(i)
22 | if (first >= 0 && first < ret) {
23 | val (j, k) = ((i + 1) % 3, (i + 2) % 3)
24 | if (first >= (minp(j) min maxp(j)) && first <= (minp(j) max maxp(j)) &&
25 | first >= (minp(k) min maxp(k)) && first <= (minp(k) max maxp(k)))
26 | ret = first
27 | }
28 | }
29 | ret
30 | }
31 | }
32 | }
33 |
34 | class Sphere(val c: Array[Double], val rad: Double) extends IntersectionOctree.IntersectionObject {
35 | def apply(dim: Int): Double = c(dim)
36 | def min(dim: Int): Double = c(dim) - rad
37 | def max(dim: Int): Double = c(dim) + rad
38 | def size: Double = rad * 2
39 | }
40 | }
--------------------------------------------------------------------------------
/src/multithreading1/Account.scala:
--------------------------------------------------------------------------------
1 | package multithreading1
2 |
3 | class Account(
4 | private var _balance: Int,
5 | val id: String) {
6 |
7 | def balance = _balance
8 |
9 | def deposit(amount: Int): Boolean = {
10 | if (amount > 0) {
11 | val oldBalance = _balance
12 | val newBalance = oldBalance + amount
13 | _balance = newBalance
14 | true
15 | } else false
16 | }
17 |
18 | def withdraw(amount: Int): Boolean = {
19 | if (amount > 0 && amount <= _balance) {
20 | val oldBalance = _balance
21 | val newBalance = oldBalance - amount
22 | _balance = newBalance
23 | true
24 | } else false
25 | }
26 | }
--------------------------------------------------------------------------------
/src/multithreading1/AccountSync.scala:
--------------------------------------------------------------------------------
1 | package multithreading1
2 |
3 | class AccountSync(
4 | private var _balance: Int,
5 | val id: String) {
6 |
7 | def balance = _balance
8 |
9 | def deposit(amount: Int): Boolean = synchronized {
10 | if (amount > 0) {
11 | val oldBalance = _balance
12 | val newBalance = oldBalance + amount
13 | _balance = newBalance
14 | true
15 | } else false
16 | }
17 |
18 | def withdraw(amount: Int): Boolean = synchronized {
19 | if (amount > 0 && amount <= _balance) {
20 | val oldBalance = _balance
21 | val newBalance = oldBalance - amount
22 | _balance = newBalance
23 | true
24 | } else false
25 | }
26 | }
--------------------------------------------------------------------------------
/src/multithreading1/SimpleExample.scala:
--------------------------------------------------------------------------------
1 | package multithreading1
2 |
3 | import scala.concurrent.Future
4 | import scala.concurrent.ExecutionContext.Implicits.global
5 |
6 | object SimpleExample extends App {
7 | Future {
8 | for(i <- 1 to 26) {
9 | println(i)
10 | Thread.sleep(10)
11 | }
12 | }
13 | for(c <- 'a' to 'z') {
14 | println(c)
15 | Thread.sleep(10)
16 | }
17 | }
--------------------------------------------------------------------------------
/src/multithreading1/SimpleThreadGUI.scala:
--------------------------------------------------------------------------------
1 | package multithreading1
2 |
3 | import scalafx.Includes._
4 | import scalafx.application.JFXApp
5 | import scalafx.scene.Scene
6 | import scalafx.scene.control.Button
7 | import scalafx.event.ActionEvent
8 |
9 | object SimpleThreadGUI extends JFXApp {
10 | stage = new JFXApp.PrimaryStage {
11 | title = "GUI Thread Demo"
12 | scene = new Scene(100, 50) {
13 | val button = new Button("Click Me")
14 | root = button
15 | button.onAction = (ae: ActionEvent) => println(Thread.currentThread().getName)
16 | }
17 | }
18 | }
--------------------------------------------------------------------------------
/src/multithreading1/ThreadBlockGUI.scala:
--------------------------------------------------------------------------------
1 | package multithreading1
2 |
3 | import scalafx.Includes._
4 | import scalafx.application.JFXApp
5 | import scalafx.scene.Scene
6 | import scalafx.scene.control.Button
7 | import scalafx.event.ActionEvent
8 |
9 | object ThreadBlockGUI extends JFXApp {
10 | stage = new JFXApp.PrimaryStage {
11 | title = "GUI Thread Demo"
12 | scene = new Scene(100, 50) {
13 | val button = new Button("Click Me")
14 | root = button
15 | button.onAction = (ae: ActionEvent) => Thread.sleep(10000)
16 | }
17 | }
18 | }
--------------------------------------------------------------------------------
/src/multithreading1/WeeksWeather.scala:
--------------------------------------------------------------------------------
1 | package multithreading1
2 |
3 | import scala.concurrent.Future
4 | import scala.concurrent.ExecutionContext.Implicits.global
5 | import scala.util.parsing.json.JSON
6 |
7 | object WeeksWeather extends App {
8 | println("Starting app.")
9 | val f1 = Future {
10 | io.Source.fromURL(
11 | "https://www.metaweather.com/api/location/search/?query=san").mkString
12 | }
13 | val f2 = f1.map(jsonStr => {
14 | val json = JSON.parseFull(jsonStr)
15 | json.get match {
16 | case lst: List[Map[String, Any]] =>
17 | lst.find(m => m("title") == "San Antonio") match {
18 | case Some(map) =>
19 | map("woeid") match {
20 | case d: Double => Some(d.toInt)
21 | case _ => None
22 | }
23 | case None =>
24 | None
25 | }
26 | case _ =>
27 | None
28 | }
29 | })
30 | val days = 1 to 5
31 | val f3 = f2.flatMap(optInt => optInt match {
32 | case Some(woeid) =>
33 | val dayFutures = days.map(day => Future {
34 | io.Source.fromURL(
35 | s"https://www.metaweather.com/api/location/$woeid/2016/5/$day/").mkString
36 | })
37 | Future.sequence(dayFutures)
38 | case None => Future { Nil }
39 | })
40 | f3.foreach(lst => lst.foreach(println))
41 | println("About to sleep")
42 | Thread.sleep(10000)
43 | println("Done")
44 | }
--------------------------------------------------------------------------------
/src/multithreading1/WeeksWeatherFor.scala:
--------------------------------------------------------------------------------
1 | package multithreading1
2 |
3 | import scala.concurrent.Future
4 | import scala.concurrent.ExecutionContext.Implicits.global
5 | import scala.util.parsing.json.JSON
6 |
7 | object WeeksWeatherFor extends App {
8 | println("Starting app.")
9 | val days = 1 to 5
10 | val future = for {
11 | jsonStr <- loadURL("https://www.metaweather.com/api/location/search/?query=san")
12 | Some(woeid) <- getWoeid(jsonStr)
13 | daysJson <- getDaysJSON(woeid, days)
14 | } {
15 | daysJson.foreach(println)
16 | }
17 | println("About to sleep")
18 | Thread.sleep(10000)
19 | println("Done")
20 |
21 | def loadURL(url: String): Future[String] = Future { io.Source.fromURL(url).mkString }
22 |
23 | def getWoeid(jsonStr: String): Future[Option[Int]] = Future {
24 | val json = JSON.parseFull(jsonStr)
25 | json.get match {
26 | case lst: List[Map[String, Any]] =>
27 | lst.find(m => m("title") == "San Antonio") match {
28 | case Some(map) =>
29 | map("woeid") match {
30 | case d: Double => Some(d.toInt)
31 | case _ => None
32 | }
33 | case None =>
34 | None
35 | }
36 | case _ =>
37 | None
38 | }
39 | }
40 |
41 | def getDaysJSON(woeid: Int, days: Seq[Int]): Future[Seq[String]] = {
42 | val dayFutures = days.map(day => loadURL(s"https://www.metaweather.com/api/location/$woeid/2016/5/$day/"))
43 | Future.sequence(dayFutures)
44 | }
45 | }
--------------------------------------------------------------------------------
/src/multithreading1/actorexamples/AskActor.scala:
--------------------------------------------------------------------------------
1 | package multithreading1.actorexamples
2 |
3 | import scala.concurrent.duration._
4 |
5 | import akka.actor.Actor
6 | import akka.actor.ActorRef
7 | import akka.pattern._
8 | import akka.util.Timeout.durationToTimeout
9 |
10 | class AskActor(val name: String) extends Actor {
11 | implicit val timeout = durationToTimeout(1.seconds)
12 | implicit val ec = context.system.dispatcher
13 | import AskActor._
14 | def receive = {
15 | case AskName =>
16 | sender ! name
17 | case AskOf(o) =>
18 | (o ? AskName).foreach(n => println(s"They said their name is $n."))
19 | }
20 | }
21 |
22 | object AskActor {
23 | case object AskName
24 | case class AskOf(otherActor: ActorRef)
25 | }
--------------------------------------------------------------------------------
/src/multithreading1/actorexamples/AskPattern.scala:
--------------------------------------------------------------------------------
1 | package multithreading1.actorexamples
2 |
3 | import scala.concurrent.duration._
4 |
5 | import akka.actor.ActorSystem
6 | import akka.actor.Props
7 | import akka.pattern.Patterns.ask
8 | import akka.util.Timeout.durationToTimeout
9 |
10 | object AskPattern extends App {
11 | val system = ActorSystem("SimpleExample")
12 | val bob = system.actorOf(Props(new AskActor("Bob")), "BobActor")
13 | val jill = system.actorOf(Props(new AskActor("Jill")), "JillActor")
14 | implicit val ec = system.dispatcher
15 |
16 | jill ! AskActor.AskOf(bob)
17 |
18 | val nameFuture = ask(jill, AskActor.AskName, 1.seconds)
19 |
20 | nameFuture.foreach { s =>
21 | println("name = "+s)
22 | }
23 |
24 | Thread.sleep(100)
25 | system.terminate()
26 | }
--------------------------------------------------------------------------------
/src/multithreading1/actorexamples/ChildActor.scala:
--------------------------------------------------------------------------------
1 | package multithreading1.actorexamples
2 |
3 | import akka.actor.Actor
4 |
5 | class ChildActor extends Actor {
6 | import ChildActor._
7 | def receive = {
8 | case ToParent =>
9 | println("Child sending Cascade to parent")
10 | context.parent ! ParentActor.Cascade
11 | case SimpleMessage =>
12 | println("Child Simple = "+self.path)
13 | }
14 | }
15 |
16 | object ChildActor {
17 | case object ToParent
18 | case object SimpleMessage
19 | }
--------------------------------------------------------------------------------
/src/multithreading1/actorexamples/CountDown.scala:
--------------------------------------------------------------------------------
1 | package multithreading1.actorexamples
2 |
3 | import akka.actor.ActorSystem
4 | import akka.actor.Props
5 |
6 | object CountDown extends App {
7 | val system = ActorSystem("CountDownExample")
8 | val actor1 = system.actorOf(Props[CountDownActor], "Actor1")
9 | val actor2 = system.actorOf(Props[CountDownActor], "Actor2")
10 |
11 | actor1 ! CountDownActor.StartCounting(10, actor2)
12 | }
--------------------------------------------------------------------------------
/src/multithreading1/actorexamples/CountDownActor.scala:
--------------------------------------------------------------------------------
1 | package multithreading1.actorexamples
2 |
3 | import akka.actor.Actor
4 | import akka.actor.ActorRef
5 |
6 | class CountDownActor extends Actor {
7 | import CountDownActor._
8 | def receive = {
9 | case StartCounting(n, o) =>
10 | println(n)
11 | o ! Count(n - 1)
12 | case Count(n) =>
13 | if (n > 0) {
14 | println(n)
15 | Thread.sleep(1000)
16 | sender ! Count(n - 1)
17 | } else {
18 | context.system.terminate()
19 | }
20 | }
21 | }
22 |
23 | object CountDownActor {
24 | case class StartCounting(n: Int, partner: ActorRef)
25 | case class Count(n: Int)
26 | }
27 |
--------------------------------------------------------------------------------
/src/multithreading1/actorexamples/HierarchyExample.scala:
--------------------------------------------------------------------------------
1 | package multithreading1.actorexamples
2 |
3 | import akka.actor.ActorSystem
4 | import akka.actor.Props
5 |
6 | object HierarchyExample extends App {
7 | val system = ActorSystem("HierarchyExample")
8 | val actor1 = system.actorOf(Props[ParentActor],"parent1")
9 | val actor2 = system.actorOf(Props[ParentActor],"parent2")
10 |
11 | val c1 = system.actorSelection("akka://HierarchyExample/user/parent1/child1")
12 | c1 ! ChildActor.ToParent
13 | val c2 = system.actorSelection("/user/parent2/child1")
14 | c2 ! ChildActor.ToParent
15 |
16 | Thread.sleep(100)
17 | system.terminate()
18 | }
--------------------------------------------------------------------------------
/src/multithreading1/actorexamples/LifecycleChild.scala:
--------------------------------------------------------------------------------
1 | package multithreading1.actorexamples
2 |
3 | import akka.actor.Actor
4 |
5 | class LifecycleChild extends Actor {
6 | println("Making a child "+self.path)
7 |
8 | import LifecycleChild._
9 | def receive = {
10 | case Throw =>
11 | println("Child Dying")
12 | throw new Exception("Something bad happened.")
13 | case SimpleMessage =>
14 | println("Child Simple = "+self.path)
15 | }
16 | override def preStart() = {
17 | super.preStart
18 | println("Prestart")
19 | }
20 | override def postStop() = {
21 | super.postStop
22 | println("Poststop")
23 | }
24 | override def preRestart(reason: Throwable, message: Option[Any]) = {
25 | super.preRestart(reason, message)
26 | println("Prerestart "+message)
27 | }
28 | override def postRestart(reason: Throwable) = {
29 | super.postRestart(reason)
30 | println("Postrestart")
31 | }
32 | }
33 |
34 | object LifecycleChild {
35 | case object Throw
36 | case object SimpleMessage
37 | }
--------------------------------------------------------------------------------
/src/multithreading1/actorexamples/LifecycleParent.scala:
--------------------------------------------------------------------------------
1 | package multithreading1.actorexamples
2 |
3 | import akka.actor.Props
4 | import akka.actor.Actor
5 | import akka.actor.OneForOneStrategy
6 | import akka.actor.SupervisorStrategy._
7 |
8 | class LifecycleParent extends Actor {
9 | override def preStart() = {
10 | context.actorOf(Props[LifecycleChild], "child1")
11 | }
12 | def receive = {
13 | case m =>
14 | println("Parent")
15 | context.children.foreach(_ ! LifecycleChild.SimpleMessage)
16 | }
17 | override val supervisorStrategy = OneForOneStrategy(loggingEnabled = false) {
18 | case ex: Exception =>
19 | println("Child had an exception")
20 | Restart
21 | }
22 | }
--------------------------------------------------------------------------------
/src/multithreading1/actorexamples/ParentActor.scala:
--------------------------------------------------------------------------------
1 | package multithreading1.actorexamples
2 |
3 | import akka.actor.Props
4 | import akka.actor.Actor
5 |
6 | class ParentActor extends Actor {
7 | override def preStart() = {
8 | context.actorOf(Props[ChildActor], "child1")
9 | context.actorOf(Props[ChildActor], "child2")
10 | context.actorOf(Props[ChildActor], "child3")
11 | }
12 |
13 | import ParentActor._
14 | def receive = {
15 | case Cascade =>
16 | println("Parent")
17 | context.children.foreach(_ ! ChildActor.SimpleMessage)
18 | }
19 | }
20 |
21 | object ParentActor {
22 | case object Cascade
23 | }
--------------------------------------------------------------------------------
/src/multithreading1/actorexamples/RouterExample.scala:
--------------------------------------------------------------------------------
1 | package multithreading1.actorexamples
2 |
3 | import akka.actor.ActorSystem
4 | import akka.actor.Actor
5 | import akka.actor.ActorRef
6 | import akka.actor.Props
7 | import akka.routing.BalancingPool
8 |
9 | object RouterExample extends App {
10 |
11 | val MaxCount = 10000
12 | val ImageSize = 500
13 |
14 | case class Complex(real: Double, imag: Double) {
15 | def +(c: Complex) = Complex(real + c.real, imag + c.imag)
16 | def *(c: Complex) = Complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real)
17 | def mag = math.sqrt(real * real + imag * imag)
18 | }
19 |
20 | def juliaStep(z: Complex, c: Complex): Complex = z * z + c
21 |
22 | def juliaCount(c: Complex): Int = {
23 | var cnt = 0
24 | var z = c
25 | while (cnt < MaxCount && z.mag < 4) {
26 | z = juliaStep(z, c)
27 | cnt += 1
28 | }
29 | cnt
30 | }
31 |
32 | case class MakeImage(xmin: Double, xmax: Double, ymin: Double, ymax: Double)
33 | case class Line(row: Int, y: Double, xmin: Double, xmax: Double)
34 | case class LineResult(row: Int, rgbs: Array[Int])
35 |
36 | class JuliaActor extends Actor {
37 | def receive = {
38 | case MakeImage(xmin, xmax, ymin, ymax) =>
39 |
40 | }
41 | }
42 |
43 | class LineActor(mandel:ActorRef) extends Actor {
44 | def receive = {
45 | case Line(r, y, xmin, xmax) =>
46 | mandel ! LineResult(r, Array.tabulate(ImageSize)(i => {
47 | val x = xmin + i * (xmax - xmin) / ImageSize
48 | juliaCount(Complex(x, y))
49 | }))
50 | }
51 | }
52 |
53 | val system = ActorSystem("JuliaSet")
54 | val actor = system.actorOf(Props[JuliaActor], "JuliaActor")
55 | val router = system.actorOf(BalancingPool(5).props(Props(new LineActor(actor))),"poolRouter")
56 |
57 | }
--------------------------------------------------------------------------------
/src/multithreading1/actorexamples/SimpleExample.scala:
--------------------------------------------------------------------------------
1 | package multithreading1.actorexamples
2 |
3 | import akka.actor.Actor
4 | import akka.actor.ActorSystem
5 | import akka.actor.Props
6 |
7 | object SimpleExample extends App {
8 | class SimpleActor extends Actor {
9 | private var counter = 0
10 |
11 | def receive = {
12 | case s: String => println("String "+s); count()
13 | case i: Int => println("Int "+i); count()
14 | }
15 |
16 | def count(): Unit = counter += 1
17 | }
18 | val system = ActorSystem("SimpleExample")
19 | val actor = system.actorOf(Props[SimpleActor], "FirstActor")
20 | actor ! "Hi"
21 | actor ! 42
22 | actor ! 'a'
23 | system.terminate()
24 | }
25 |
26 |
--------------------------------------------------------------------------------
/src/multithreading1/actorexamples/SupervisorExample.scala:
--------------------------------------------------------------------------------
1 | package multithreading1.actorexamples
2 |
3 | import akka.actor.ActorSystem
4 | import akka.actor.Props
5 |
6 | object SupervisorExample extends App {
7 | val system = ActorSystem("SupervisorExample")
8 | val actor1 = system.actorOf(Props[LifecycleParent], "parent1")
9 |
10 | val c1 = system.actorSelection("akka://SupervisorExample/user/parent1/child1")
11 | c1 ! LifecycleChild.Throw
12 | Thread.sleep(10)
13 | c1 ! LifecycleChild.SimpleMessage
14 |
15 | Thread.sleep(100)
16 | system.terminate()
17 | }
--------------------------------------------------------------------------------
/src/multithreading1/drawing/Commands.scala:
--------------------------------------------------------------------------------
1 | package multithreading1.drawing
2 |
3 | import stackqueue.util.RPNCalc
4 | import scalafx.application.Platform
5 |
6 | object Commands {
7 | private val commands = Map[String, (String, Drawing) => Any](
8 | "add" -> ((rest, d) => rest.trim.split(" +").map(_.toInt).sum),
9 | "echo" -> ((rest, d) => rest.trim),
10 | "refresh" -> ((rest, d) => Platform.runLater { d.draw() } ),
11 | "rpn" -> ((rest,d) => (RPNCalc(rest.trim.split(" +"), d.vars))),
12 | "set" -> ((rest,d) => {
13 | val parts = rest.trim.split(" +")
14 | d.vars(parts(0)) = parts(1).toDouble
15 | parts(0)+" = "+parts(1)
16 | }),
17 | "freeze" -> ((rest,d) => Thread.sleep(rest.trim.toInt*1000)))
18 |
19 | def apply(input: String, drawing: Drawing): Any = {
20 | val spaceIndex = input.indexOf(' ')
21 | val (command, rest) = if (spaceIndex < 0) (input.toLowerCase(), "")
22 | else (input.take(spaceIndex).toLowerCase(), input.drop(spaceIndex))
23 | if (commands.contains(command)) commands(command)(rest, drawing) else "Not a valid command."
24 | }
25 | }
--------------------------------------------------------------------------------
/src/multithreading1/drawing/DrawRectangle.scala:
--------------------------------------------------------------------------------
1 | package multithreading1.drawing
2 |
3 | import scalafx.Includes._
4 | import scalafx.scene.canvas.GraphicsContext
5 | import scalafx.scene.paint.Color
6 | import scalafx.scene.Node
7 | import scalafx.scene.layout.VBox
8 | import scalafx.scene.control.TextField
9 | import scalafx.scene.control.ColorPicker
10 | import scalafx.event.ActionEvent
11 | import scalafx.scene.layout.Priority
12 |
13 | class DrawRectangle(
14 | d: Drawing,
15 | private var _x: Double,
16 | private var _y: Double,
17 | private var _width: Double,
18 | private var _height: Double,
19 | private var _color: Color) extends Drawable(d) {
20 |
21 | private var propPanel: Option[Node] = None
22 |
23 | override def toString = "Rectangle"
24 |
25 | def draw(gc: GraphicsContext): Unit = {
26 | gc.fill = _color
27 | gc.fillRect(_x, _y, _width, _height)
28 | }
29 |
30 | def propertiesPanel(): Node = {
31 | if (propPanel.isEmpty) {
32 | val panel = new VBox
33 | val xField = DrawingMain.labeledTextField("x", _x.toString, s => { _x = s.toDouble; drawing.draw() })
34 | val yField = DrawingMain.labeledTextField("y", _y.toString, s => { _y = s.toDouble; drawing.draw() })
35 | val widthField = DrawingMain.labeledTextField("width", _width.toString, s => { _width = s.toDouble; drawing.draw() })
36 | val heightField = DrawingMain.labeledTextField("height", _height.toString, s => { _height = s.toDouble; drawing.draw() })
37 | val colorPicker = new ColorPicker(_color)
38 | colorPicker.onAction = (ae: ActionEvent) => {
39 | _color = colorPicker.value.value
40 | drawing.draw()
41 | }
42 | panel.children = List(xField, yField, widthField, heightField, colorPicker)
43 | propPanel = Some(panel)
44 | }
45 | propPanel.get
46 | }
47 | }
--------------------------------------------------------------------------------
/src/multithreading1/drawing/DrawText.scala:
--------------------------------------------------------------------------------
1 | package multithreading1.drawing
2 |
3 | import scalafx.Includes._
4 | import scalafx.scene.canvas.GraphicsContext
5 | import scalafx.scene.paint.Color
6 | import scalafx.scene.Node
7 | import scalafx.scene.layout.VBox
8 | import scalafx.scene.control.ColorPicker
9 | import scalafx.event.ActionEvent
10 |
11 | class DrawText(
12 | d: Drawing,
13 | private var _x: Double,
14 | private var _y: Double,
15 | private var _text: String,
16 | private var _color: Color) extends Drawable(d) {
17 |
18 | private var propPanel: Option[Node] = None
19 |
20 | override def toString = "Text: "+_text
21 |
22 | def draw(gc: GraphicsContext): Unit = {
23 | gc.fill = _color
24 | gc.fillText(_text, _x, _y)
25 | }
26 |
27 | def propertiesPanel(): Node = {
28 | if (propPanel.isEmpty) {
29 | val panel = new VBox
30 | val textField = DrawingMain.labeledTextField("Text", _text, s => { _text = s; drawing.draw() })
31 | val xField = DrawingMain.labeledTextField("x", _x.toString, s => { _x = s.toDouble; drawing.draw() })
32 | val yField = DrawingMain.labeledTextField("y", _y.toString, s => { _y = s.toDouble; drawing.draw() })
33 | val colorPicker = new ColorPicker(_color)
34 | colorPicker.onAction = (ae: ActionEvent) => {
35 | _color = colorPicker.value.value
36 | drawing.draw()
37 | }
38 | panel.children = List(textField, xField, yField, colorPicker)
39 | propPanel = Some(panel)
40 | }
41 | propPanel.get
42 | }
43 | }
--------------------------------------------------------------------------------
/src/multithreading1/drawing/Drawable.scala:
--------------------------------------------------------------------------------
1 | package multithreading1.drawing
2 |
3 | import scalafx.scene.canvas.GraphicsContext
4 | import scalafx.scene.Node
5 |
6 | abstract class Drawable(val drawing: Drawing) {
7 | def draw(gc: GraphicsContext): Unit
8 | def propertiesPanel(): Node
9 | }
--------------------------------------------------------------------------------
/src/multithreading1/drawing/Drawing.scala:
--------------------------------------------------------------------------------
1 | package multithreading1.drawing
2 |
3 | import collection.mutable
4 | import scalafx.scene.canvas.GraphicsContext
5 | import scalafx.scene.control.TreeItem
6 | import scalafx.scene.paint.Color
7 |
8 | class Drawing(private var gc: GraphicsContext) {
9 | private var root = new DrawTransform(this)
10 |
11 | private[drawing] val vars = mutable.Map[String, Double]()
12 |
13 | def draw(): Unit = {
14 | gc.fill = Color.White
15 | gc.fillRect(0, 0, 2000, 2000)
16 | root.draw(gc)
17 | }
18 |
19 | def makeTree: TreeItem[Drawable] = {
20 | def helper(d: Drawable): TreeItem[Drawable] = d match {
21 | case dt: DrawTransform =>
22 | val item = new TreeItem(d)
23 | item.children = dt.children.map(c => helper(c))
24 | item
25 | case _ => new TreeItem(d)
26 | }
27 | helper(root)
28 | }
29 | }
--------------------------------------------------------------------------------
/src/multithreading2/CountAtomic.scala:
--------------------------------------------------------------------------------
1 | package multithreading2
2 |
3 | import java.util.concurrent.atomic.AtomicInteger
4 |
5 | object CountAtomic extends App {
6 | var cnt = new AtomicInteger(0)
7 | for (i <- (1 to 10000000).par) {
8 | cnt.incrementAndGet()
9 | }
10 | println(cnt.get)
11 | }
--------------------------------------------------------------------------------
/src/multithreading2/FutureJoining.scala:
--------------------------------------------------------------------------------
1 | package multithreading2
2 |
3 | import scala.concurrent.Future
4 | import scala.concurrent.ExecutionContext.Implicits.global
5 |
6 | object FutureJoining extends App {
7 | val futures = for (i <- 1 to 10) yield Future {
8 | // Do something here
9 | }
10 | Future.sequence(futures).foreach(values => {
11 | // Do other stuff that needs the futures to have finished.
12 | })
13 | }
--------------------------------------------------------------------------------
/src/multithreading2/NonAtomicLocking.scala:
--------------------------------------------------------------------------------
1 | package multithreading2
2 |
3 | object NonAtomicLocking extends App {
4 |
5 | // Note that this code doesn't do what it is attempting because the checking and setting of
6 | // the isSafe var is not atomic.
7 | var isSafe = true
8 | var cnt = 0
9 | for (i <- (1 to 1000000000).par) {
10 | if(isSafe) {
11 | isSafe = false
12 | cnt += 1
13 | isSafe = true
14 | }
15 | }
16 | println(cnt)
17 | }
--------------------------------------------------------------------------------
/src/multithreading2/ParallelFactorials.scala:
--------------------------------------------------------------------------------
1 | package multithreading2
2 |
3 | import java.util.concurrent.ExecutorService
4 | import java.util.concurrent.Callable
5 | import java.util.concurrent.Executors
6 | import scala.concurrent.Future
7 | import scala.concurrent.ExecutionContext.Implicits.global
8 | import scala.concurrent.Await
9 | import scala.concurrent.duration._
10 |
11 | object ParallelFactorials extends App {
12 | def fact(n: BigInt) = (BigInt(1) to n).product
13 |
14 | def parallelFactorial(n: BigInt, es: ExecutorService, nThreads: Int): BigInt = {
15 | val block = n / nThreads
16 | val rem = n % nThreads
17 | var i = BigInt(1)
18 | val futures = Array.tabulate(nThreads)(j => es.submit(new Callable[BigInt] {
19 | def call(): BigInt = {
20 | val start = i
21 | val end = start + block + (if (BigInt(j) < rem) 1 else 0)
22 | i = end
23 | (start until end).product
24 | }
25 | }))
26 | futures.map(_.get).product
27 | }
28 |
29 | def parallelFactorial2(n: BigInt, es: ExecutorService, nThreads: Int): BigInt = {
30 | val futures = Array.tabulate(nThreads)(j => es.submit(new Callable[BigInt] {
31 | def call(): BigInt = {
32 | (BigInt(j + 1) to n by nThreads).product
33 | }
34 | }))
35 | futures.map(_.get).product
36 | }
37 |
38 | def parallelFactorial(n: BigInt, nThreads: Int): Future[BigInt] = {
39 | val futures = List.tabulate(nThreads)(j => Future {
40 | (BigInt(j + 1) to n by nThreads).product
41 | })
42 | Future.sequence(futures).map(_.product)
43 | }
44 |
45 | def parallelFactorial(n: BigInt) = (BigInt(1) to n).par.product
46 |
47 | // Speed testing
48 | val es = Executors.newCachedThreadPool()
49 | multithreading1.RandomCodeSegments.timeCode(fact(30000))
50 | multithreading1.RandomCodeSegments.timeCode(parallelFactorial(30000, es, 4))
51 | multithreading1.RandomCodeSegments.timeCode(parallelFactorial2(30000, es, 4))
52 | multithreading1.RandomCodeSegments.timeCode(Await.result(parallelFactorial(30000, 4), 10.seconds))
53 | multithreading1.RandomCodeSegments.timeCode(parallelFactorial(30000))
54 | es.shutdown()
55 |
56 | }
--------------------------------------------------------------------------------
/src/multithreading2/ReadTimeout.scala:
--------------------------------------------------------------------------------
1 | package multithreading2
2 |
3 | import io.StdIn._
4 |
5 | object ReadTimeout extends App {
6 | val countThread = new Thread {
7 | override def run: Unit = {
8 | for (i <- 10 to 1 by -1) {
9 | println(i)
10 | Thread.sleep(1000)
11 | }
12 | println("Time's up.")
13 | sys.exit(0)
14 | }
15 | }
16 | println("Enter your age.")
17 | countThread.start()
18 | val age = readInt()
19 | if (age < 18) println("Sorry, you can't come here.")
20 | else println("Welcome.")
21 | sys.exit(0)
22 | }
--------------------------------------------------------------------------------
/src/multithreading2/ReadTimeout2.scala:
--------------------------------------------------------------------------------
1 | package multithreading2
2 |
3 | import io.StdIn._
4 |
5 | object ReadTimeout2 extends App {
6 | var answered = false
7 | val countThread = new Thread {
8 | override def run():Unit = {
9 | var i = 10
10 | while (!answered && i > 0) {
11 | println(i)
12 | Thread.sleep(1000)
13 | i -= 1
14 | }
15 | if (!answered) {
16 | println("Time's up.")
17 | sys.exit(0)
18 | }
19 | }
20 | }
21 | println("Enter your age.")
22 | countThread.start()
23 | val age = readInt()
24 | answered = true
25 | if (age < 18) println("Sorry, you can't come here.")
26 | else println("Welcome.")
27 | }
--------------------------------------------------------------------------------
/src/multithreading2/ReadTimeout3.scala:
--------------------------------------------------------------------------------
1 | package multithreading2
2 |
3 | import io.StdIn._
4 |
5 | object ReadTimeout3 extends App {
6 | var answered = false
7 | var timeUp = false
8 | val countThread = new Thread {
9 | override def run {
10 | var i = 10
11 | while (!answered && i > 0) {
12 | println(i)
13 | Thread.sleep(1000)
14 | i -= 1
15 | }
16 | if (!answered) {
17 | println("Time's up.")
18 | timeUp = true
19 | }
20 | }
21 | }
22 | println("Enter your age.")
23 | countThread.start()
24 | while (!timeUp && !Console.in.ready) {
25 | Thread.sleep(10)
26 | }
27 | if (!timeUp) {
28 | val age = readInt()
29 | answered = true
30 | if (age < 18) println("Sorry, you can't come here.")
31 | else println("Welcome.")
32 | }
33 | }
--------------------------------------------------------------------------------
/src/multithreading2/ThreadJoining.scala:
--------------------------------------------------------------------------------
1 | package multithreading2
2 |
3 | object ThreadJoining extends App {
4 | val threads = for(i <- 1 to 10) yield {
5 | new Thread {
6 | override def run():Unit = {
7 | // Do something here
8 | }
9 | }
10 | }
11 | threads.foreach(_.start())
12 |
13 | // This will cause the main thread to pause until the other threads are done.
14 | threads.foreach(_.join())
15 | // Do other stuff that needs the threads to have finished.
16 | }
--------------------------------------------------------------------------------
/src/multithreading2/WaitCounting.scala:
--------------------------------------------------------------------------------
1 | package multithreading2
2 |
3 | object WaitCounting extends App {
4 | val numThreads = 3
5 | val threads = Array.tabulate(numThreads)(i => new Thread {
6 | override def run():Unit = {
7 | println("Start "+i)
8 | for (j <- 1 to 5) {
9 | WaitCounting.synchronized {
10 | WaitCounting.wait()
11 | println(i+" : "+j)
12 | WaitCounting.notify()
13 | }
14 | }
15 | }
16 | })
17 | threads.foreach(_.start)
18 | Thread.sleep(1000)
19 | println("First notify.")
20 | synchronized { notify() }
21 | }
--------------------------------------------------------------------------------
/src/multithreading2/WaitCountingSafe.scala:
--------------------------------------------------------------------------------
1 | package multithreading2
2 |
3 | object WaitCountingSafe extends App {
4 | val numThreads = 3
5 | var handOff = Array.fill(numThreads)(false)
6 | val threads = Array.tabulate(numThreads)(i => new Thread {
7 | override def run {
8 | println("Start "+i)
9 | for (j <- 1 to 5) {
10 | WaitCountingSafe.synchronized {
11 | while (!handOff(i)) {
12 | WaitCountingSafe.wait()
13 | }
14 | handOff(i) = false
15 | println(i+" : "+j)
16 | handOff((i + 1) % numThreads) = true
17 | WaitCountingSafe.notifyAll()
18 | }
19 | }
20 | }
21 | })
22 | threads.foreach(_.start)
23 | Thread.sleep(1000)
24 | println("First notify.")
25 | handOff(0) = true
26 | synchronized { notifyAll() }
27 | }
--------------------------------------------------------------------------------
/src/networking/Datagram.scala:
--------------------------------------------------------------------------------
1 | package networking
2 |
3 | import java.net.DatagramPacket
4 | import java.net.DatagramSocket
5 | import java.net.InetAddress
6 | import scala.collection.mutable
7 |
8 | object Datagram extends App {
9 | def packDouble(d: Double, v: mutable.IndexedSeq[Byte]):Unit = {
10 | var dlong = java.lang.Double.doubleToLongBits(d)
11 | for (i <- v.indices) {
12 | v(i) = dlong.toByte
13 | dlong >>= 8
14 | }
15 | }
16 |
17 | def unpackDouble(v: mutable.IndexedSeq[Byte]): Double = {
18 | val dlong = v.foldRight(0L)((b, dl) => (dl << 8) | (b & 0xff))
19 | java.lang.Double.longBitsToDouble(dlong)
20 | }
21 |
22 | def packArray(ds: Array[Double]): Array[Byte] = {
23 | val ret = new Array[Byte](8 * ds.length)
24 | for (i <- ds.indices) packDouble(ds(i), ret.view(8 * i, 8 * (i + 1)))
25 | ret
26 | }
27 |
28 | if (args.length > 1) {
29 | val socket = new DatagramSocket()
30 | val data = packArray(args.map(_.toDouble))
31 | val packet = new DatagramPacket(data, data.length, InetAddress.getByName("localhost"), 8000)
32 | socket.send(packet)
33 | } else if (args.length == 1) {
34 | val socket = new DatagramSocket(8000)
35 | val num = args(0).toInt
36 | val data = new Array[Byte](8 * num)
37 | val packet = new DatagramPacket(data, data.length)
38 | socket.receive(packet)
39 | for (i <- 0 until 8 * num by 8) println(unpackDouble(data.view(i, i + 8)))
40 | } else println("Specify one int for number to read or multiple doubles to send.")
41 | }
--------------------------------------------------------------------------------
/src/networking/DoClient.scala:
--------------------------------------------------------------------------------
1 | package networking
2 |
3 | import java.net.Socket
4 |
5 | object DoClient extends App {
6 | val clientSock = new Socket("localhost", 8000)
7 | // Stuff to communicate across clientSock
8 | }
--------------------------------------------------------------------------------
/src/networking/DoServer.scala:
--------------------------------------------------------------------------------
1 | package networking
2 |
3 | import java.net.ServerSocket
4 |
5 | object DoServer extends App {
6 | val ss = new ServerSocket(8000)
7 | val serverSock = ss.accept()
8 | // Stuff to communicate across serverSock
9 | }
--------------------------------------------------------------------------------
/src/networking/RandomNetworkingCode.scala:
--------------------------------------------------------------------------------
1 | package networking
2 |
3 | import java.net.URL
4 | import java.io.BufferedInputStream
5 | import scala.collection.mutable
6 |
7 | object RandomNetworkingCode extends App {
8 | val scalaURL = new URL("http://www.scala-lang.org/")
9 |
10 | {
11 | val urlis = new BufferedInputStream(scalaURL.openStream())
12 | val buffer = mutable.Buffer[Byte]()
13 | var res = urlis.read()
14 | while (res >= 0) {
15 | buffer += res.toByte
16 | res = urlis.read()
17 | }
18 | val contents = new String(buffer.toArray)
19 | }
20 |
21 | {
22 | val connection = scalaURL.openConnection()
23 | val urlis = new BufferedInputStream(connection.getInputStream())
24 | val buffer = new Array[Byte](connection.getContentLength)
25 | urlis.read(buffer)
26 | val contents = new String(buffer)
27 | }
28 |
29 | {
30 | val url = new URL("http://www.cs.trinity.edu/~mlewis/banish.gif")
31 | url.getContent match {
32 | case img:java.awt.Image => println("Image")
33 | case c => println("Not image "+c)
34 | }
35 | }
36 | }
--------------------------------------------------------------------------------
/src/networking/chat/ChatClient.scala:
--------------------------------------------------------------------------------
1 | package networking.chat
2 |
3 | import io.StdIn.readLine
4 | import java.io.PrintStream
5 | import java.net.Socket
6 | import java.util.Scanner
7 | import scala.annotation.tailrec
8 | import scala.concurrent.Future
9 | import scala.concurrent.ExecutionContext.Implicits.global
10 |
11 | object ChatClient extends App {
12 | if (args.isEmpty) {
13 | println("Usage: scala ChatClient host [port]")
14 | } else {
15 | val port = if (args.length > 1) args(1).toInt else 8000
16 | val sock = new Socket(args(0), port)
17 | val sc = new Scanner(sock.getInputStream())
18 | val ps = new PrintStream(sock.getOutputStream())
19 | println("What is your handle for the chat room?")
20 | val name = readLine()
21 | ps.println(name)
22 | val response = sc.nextLine()
23 | if (response != ":quit") {
24 | Future { incoming(sc) }
25 | println("Welcome! Begin chatting.")
26 | outgoing(ps)
27 | } else {
28 | println("The server has rejected you.")
29 | }
30 | sock.close()
31 | }
32 |
33 | @tailrec private def incoming(sc: Scanner) {
34 | val line = sc.nextLine()
35 | println(line)
36 | incoming(sc)
37 | }
38 |
39 | @tailrec private def outgoing(ps: PrintStream) {
40 | print("> ")
41 | val input = readLine().trim
42 | ps.println(input)
43 | if (input != ":quit") outgoing(ps)
44 | }
45 | }
--------------------------------------------------------------------------------
/src/networking/chat/RMIServer.scala:
--------------------------------------------------------------------------------
1 | package networking.chat
2 |
3 | import java.rmi.Naming
4 | import java.rmi.RemoteException
5 | import java.rmi.server.UnicastRemoteObject
6 | import javax.management.remote.rmi.RMIServerImpl
7 | import scala.collection.mutable
8 | import java.rmi.registry.LocateRegistry
9 |
10 | object RMIServer extends UnicastRemoteObject with App with RemoteServer {
11 | LocateRegistry.createRegistry(1099)
12 | Naming.rebind("ChatServer", this)
13 |
14 | private val clients = mutable.Buffer[RemoteClient]()
15 | private var history = mutable.ListBuffer("Server Started\n")
16 |
17 | def connect(client: RemoteClient): String = {
18 | clients += client
19 | sendUpdate
20 | history.mkString("\n")+"\n"
21 | }
22 |
23 | def disconnect(client: RemoteClient) {
24 | clients -= client
25 | sendUpdate
26 | }
27 |
28 | def getClients: Seq[RemoteClient] = clients
29 |
30 | def publicMessage(client: RemoteClient, text: String) {
31 | history += client.name+" : "+text
32 | if (history.length > 10) history.remove(0)
33 | }
34 |
35 | private def sendUpdate: Unit = {
36 | val deadClients = clients.filter(c =>
37 | try {
38 | c.name
39 | false
40 | } catch {
41 | case ex: RemoteException => true
42 | })
43 | clients --= deadClients
44 | clients.foreach(_.clientUpdate(clients))
45 | }
46 | }
--------------------------------------------------------------------------------
/src/networking/chat/RemoteClient.scala:
--------------------------------------------------------------------------------
1 | package networking.chat
2 |
3 | @remote trait RemoteClient {
4 | def name: String
5 | def message(sender: RemoteClient, text: String): Unit
6 | def clientUpdate(clients: Seq[RemoteClient]): Unit
7 | }
--------------------------------------------------------------------------------
/src/networking/chat/RemoteServer.scala:
--------------------------------------------------------------------------------
1 | package networking.chat
2 |
3 | @remote trait RemoteServer {
4 | def connect(client: RemoteClient): String
5 | def disconnect(client: RemoteClient): Unit
6 | def getClients: Seq[RemoteClient]
7 | def publicMessage(client: RemoteClient, text: String): Unit
8 | }
--------------------------------------------------------------------------------
/src/networking/drawing/CollaborationServer.scala:
--------------------------------------------------------------------------------
1 | package networking.drawing
2 |
3 | import java.rmi.RemoteException
4 | import java.rmi.server.UnicastRemoteObject
5 |
6 | import scala.collection.mutable
7 |
8 | @remote trait RemoteCollaborationServer {
9 | def joinCollaboration(col: RemoteCollaborator): (Array[RemoteCollaborator], Array[(String, Drawing)])
10 | def addDrawing(title: String, drawing: Drawing): Unit
11 | }
12 |
13 | class CollaborationServer extends UnicastRemoteObject with RemoteCollaborationServer {
14 | private val collaborators = mutable.Buffer[RemoteCollaborator]()
15 | private val drawings = mutable.Buffer[(String, Drawing)]()
16 |
17 | def joinCollaboration(col: RemoteCollaborator): (Array[RemoteCollaborator], Array[(String, Drawing)]) = {
18 | collaborators += col
19 | (collaborators.toArray, drawings.toArray)
20 | }
21 |
22 | def addDrawing(title: String, drawing: Drawing): Unit = {
23 | drawings += title -> drawing
24 | for (c <- collaborators) {
25 | try {
26 | c.addDrawing(title, drawing)
27 | } catch {
28 | case ex: RemoteException =>
29 | }
30 | }
31 | }
32 | }
--------------------------------------------------------------------------------
/src/networking/drawing/Commands.scala:
--------------------------------------------------------------------------------
1 | package networking.drawing
2 |
3 | import stackqueue.util.RPNCalc
4 | import scalafx.application.Platform
5 |
6 | object Commands {
7 | private val commands = Map[String, (String, Drawing) => Any](
8 | "add" -> ((rest, d) => rest.trim.split(" +").map(_.toInt).sum),
9 | "echo" -> ((rest, d) => rest.trim),
10 | "refresh" -> ((rest, d) => Platform.runLater { d.draw() } ),
11 | "rpn" -> ((rest,d) => (RPNCalc(rest.trim.split(" +"), d.vars))),
12 | "set" -> ((rest,d) => {
13 | val parts = rest.trim.split(" +")
14 | d.vars(parts(0)) = parts(1).toDouble
15 | parts(0)+" = "+parts(1)
16 | }),
17 | "freeze" -> ((rest,d) => Thread.sleep(rest.trim.toInt*1000)))
18 |
19 | def apply(input: String, drawing: Drawing): Any = {
20 | val spaceIndex = input.indexOf(' ')
21 | val (command, rest) = if (spaceIndex < 0) (input.toLowerCase(), "")
22 | else (input.take(spaceIndex).toLowerCase(), input.drop(spaceIndex))
23 | if (commands.contains(command)) commands(command)(rest, drawing) else "Not a valid command."
24 | }
25 | }
--------------------------------------------------------------------------------
/src/networking/drawing/Drawable.scala:
--------------------------------------------------------------------------------
1 | package networking.drawing
2 |
3 | import scalafx.scene.canvas.GraphicsContext
4 | import scalafx.scene.Node
5 |
6 | abstract class Drawable(val drawing: Drawing) extends Serializable {
7 | def draw(gc: GraphicsContext): Unit
8 | def propertiesPanel(): Node
9 | def toXML: xml.Node
10 | }
11 |
12 | object Drawable {
13 | def makeDrawable(n: xml.Node, d: Drawing): Drawable = {
14 | (n \ "@type").text match {
15 | case "rectangle" => DrawRectangle(n, d)
16 | case "text" => DrawText(n, d)
17 | case "transform" => DrawTransform(n, d)
18 | case "maze" => DrawMaze(n, d)
19 | case "mandelbrot" => DrawMandelbrot(n, d)
20 | case "julia" => DrawJulia(n, d)
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/src/networking/drawing/Drawing.scala:
--------------------------------------------------------------------------------
1 | package networking.drawing
2 |
3 | import collection.mutable
4 | import scalafx.scene.canvas.GraphicsContext
5 | import scalafx.scene.control.TreeItem
6 | import scalafx.scene.paint.Color
7 |
8 | class Drawing(private[drawing] val vars: mutable.Map[String, Double]) extends Serializable {
9 | private var root = DrawTransform(this)
10 | @transient private var gc: GraphicsContext = null
11 |
12 | def graphicsContext_=(g: GraphicsContext): Unit = {
13 | gc = g
14 | }
15 |
16 | def graphicsContext = gc
17 |
18 | def draw(): Unit = {
19 | if (gc != null) {
20 | gc.fill = Color.White
21 | gc.fillRect(0, 0, 2000, 2000)
22 | root.draw(gc)
23 | }
24 | }
25 |
26 | def drawTo(tmpGC: GraphicsContext): Unit = {
27 | tmpGC.fill = Color.White
28 | tmpGC.fillRect(0, 0, 2000, 2000)
29 | root.draw(tmpGC)
30 | }
31 |
32 | def makeTree: TreeItem[Drawable] = {
33 | def helper(d: Drawable): TreeItem[Drawable] = d match {
34 | case dt: DrawTransform =>
35 | val item = new TreeItem(d)
36 | item.children = dt.children.map(c => helper(c))
37 | item
38 | case _ => new TreeItem(d)
39 | }
40 | helper(root)
41 | }
42 |
43 | def toXML: xml.Node = {
44 |
45 | { root.toXML }
46 | { for ((k, v) <- vars) yield }
47 |
48 | }
49 | }
50 |
51 | object Drawing {
52 | def apply(): Drawing = {
53 | new Drawing(mutable.Map())
54 | }
55 |
56 | def apply(n: xml.Node): Drawing = {
57 | val vars = mutable.Map((n \ "var").map(vnode => (vnode \ "@key").text -> (vnode \ "@value").text.toDouble): _*)
58 | val drawing = new Drawing(vars)
59 | drawing.root = DrawTransform(n \ "drawable", drawing)
60 | drawing
61 | }
62 |
63 | def colorToXML(color: Color): xml.Node = {
64 |
65 | }
66 |
67 | def xmlToColor(n: xml.NodeSeq): Color = {
68 | Color((n \ "@red").text.toDouble, (n \ "@green").text.toDouble, (n \ "@blue").text.toDouble, (n \ "@opacity").text.toDouble)
69 | }
70 | }
--------------------------------------------------------------------------------
/src/oobasics/GradeBook.scala:
--------------------------------------------------------------------------------
1 | package oobasics
2 |
3 | object GradeBook {
4 | def main(args: Array[String]): Unit = {
5 | val student = new Student("Jane", "Doe", List(97, 80), List(100), List(89))
6 | printGrade(student)
7 | }
8 |
9 | def printGrade(s:Student):Unit = {
10 | println(s.firstName+" "+s.lastName)
11 | println(s.grade)
12 | }
13 | }
--------------------------------------------------------------------------------
/src/oobasics/Student.scala:
--------------------------------------------------------------------------------
1 | package oobasics
2 |
3 | class Student(
4 | val firstName: String,
5 | val lastName: String,
6 | private var _quizzes: List[Int] = Nil,
7 | private var _assignments: List[Int] = Nil,
8 | private var _tests: List[Int] = Nil) {
9 | require(_quizzes.forall(q => q >= -20 && q <= 120), "Quiz grades must be in the range of [-20, 120].")
10 | require(_assignments.forall(a => a >= -20 && a <= 120), "Assignment grades must be in the range of [-20, 120].")
11 | require(_tests.forall(t => t >= -20 && t <= 120), "Test grades must be in the range of [-20, 120].")
12 |
13 | def quizAverage: Double = if (_quizzes.isEmpty) 0 else _quizzes.sum.toDouble / _quizzes.length
14 |
15 | def assignmentAverage: Double = if (_assignments.isEmpty) 0 else _assignments.sum.toDouble / _assignments.length
16 |
17 | def testAverage: Double = if (_tests.isEmpty) 0 else _tests.sum.toDouble / _tests.length
18 |
19 | def grade: Double = quizAverage * 0.2 + assignmentAverage * 0.5 + testAverage * 0.3
20 |
21 | def addQuiz(newQuiz: Int): Boolean = {
22 | if (newQuiz >= -20 && newQuiz <= 120) {
23 | _quizzes ::= newQuiz
24 | true
25 | } else false
26 | }
27 |
28 | def addAssignment(newAssignment: Int): Boolean = {
29 | if (newAssignment >= -20 && newAssignment <= 120) {
30 | _assignments ::= newAssignment
31 | true
32 | } else false
33 | }
34 |
35 | def addTest(newTest: Int): Boolean = {
36 | if (newTest >= -20 && newTest <= 120) {
37 | _tests ::= newTest
38 | true
39 | } else false
40 | }
41 |
42 | def quizzes = _quizzes
43 |
44 | def assignments = _assignments
45 |
46 | def tests = _tests
47 | }
48 |
--------------------------------------------------------------------------------
/src/oobasics/bank/Account.scala:
--------------------------------------------------------------------------------
1 | package oobasics.bank
2 |
3 | /**
4 | * Represents an account with the bank. Potentially a checking or savings account.
5 | */
6 | class Account(
7 | private var _balance: Int,
8 | val customer: Customer,
9 | val id: String) {
10 |
11 | customer.addAccount(this) // Make sure the customer knows about this account.
12 |
13 | /**
14 | * Provides public access to the current balance for this account.
15 | * @return the value of the balance.
16 | */
17 | def balance = _balance
18 |
19 | /**
20 | * Makes a deposit to the account. Deposit values must be positive.
21 | * @param amount the amount of money to deposit.
22 | * @return tells is the deposit occurred successfully.
23 | */
24 | def deposit(amount: Int): Boolean = {
25 | if (amount > 0) {
26 | _balance += amount
27 | true
28 | } else false
29 | }
30 |
31 | /**
32 | * Makes a withdraw from the account. The amount must be positive and less
33 | * than or equal to the current balance.
34 | * @param amount the amount to withdraw.
35 | * @return tells if the withdraw occurred successfully.
36 | */
37 | def withdraw(amount: Int): Boolean = {
38 | if (amount > 0 && amount <= _balance) {
39 | _balance -= amount
40 | true
41 | } else false
42 | }
43 | }
--------------------------------------------------------------------------------
/src/oobasics/bank/Address.scala:
--------------------------------------------------------------------------------
1 | package oobasics.bank
2 |
3 | class Address(val lines: List[String]) {
4 | // TODO - Code to verify that this is a valid address.
5 | }
--------------------------------------------------------------------------------
/src/oobasics/bank/Loan.scala:
--------------------------------------------------------------------------------
1 | package oobasics.bank
2 |
3 | /**
4 | * Represents a loan that the bank has made to a customer.
5 | */
6 | class Loan(
7 | private var _balance: Int,
8 | val customer: Customer,
9 | val id: String) {
10 |
11 | customer.addLoan(this) // Add this loan to the customer.
12 |
13 | /**
14 | * Provides public access to the balance left on this loan.
15 | * @return the value of the balance.
16 | */
17 | def balance = _balance
18 |
19 | /**
20 | * Make a payment on this loan. Only works for amounts greater than zero and
21 | * less than or equal to the current balance.
22 | * @param amount the amount of the current payment.
23 | * @return tells if the payment went through successfully.
24 | */
25 | def payment(amount: Int): Boolean = {
26 | if (amount > 0 && amount <= _balance) {
27 | _balance -= amount
28 | true
29 | } else false
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/oobasics/bank/PhoneNumber.scala:
--------------------------------------------------------------------------------
1 | package oobasics.bank
2 |
3 | class PhoneNumber(val value: String) {
4 | // TODO - Code that will verify this is a valid phone number.
5 | }
--------------------------------------------------------------------------------
/src/oodetails/Account.scala:
--------------------------------------------------------------------------------
1 | package oodetails
2 |
3 | /**
4 | * This is a place holder put here just to let this compile in this package without duplicating all the rest of the
5 | * bank example.
6 | */
7 | class Customer {
8 | def addAccount(acc: Account) = ???
9 | }
10 |
11 | /**
12 | * Represents an account with the bank. Potentially a checking or savings account.
13 | */
14 | class Account private(
15 | private var _balance: Int,
16 | val customer: Customer,
17 | val id: String) {
18 |
19 | customer.addAccount(this) // Make sure the customer knows about this account.
20 |
21 | def this(c:Customer, id:String) = this(0, c, id)
22 |
23 | /**
24 | * Provides public access to the current balance for this account.
25 | * @return the value of the balance.
26 | */
27 | def balance = _balance
28 |
29 | /**
30 | * This provides the ability to do assignment to the balance with
31 | * checks that go through deposit and withdraw.
32 | */
33 | def balance_=(newBalance: Int): Unit = {
34 | if (newBalance > _balance) deposit(newBalance - _balance)
35 | else if (newBalance < _balance) withdraw(_balance - newBalance)
36 | }
37 |
38 | /**
39 | * Makes a deposit to the account. Deposit values must be positive.
40 | * @param amount the amount of money to deposit.
41 | * @return tells is the deposit occurred successfully.
42 | */
43 | def deposit(amount: Int): Boolean = {
44 | if (amount > 0) {
45 | _balance += amount
46 | true
47 | } else false
48 | }
49 |
50 | /**
51 | * Makes a withdraw from the account. The amount must be positive and less
52 | * than the current balance.
53 | * @param amount the amount to withdraw.
54 | * @return tells if the withdraw occurred successfully.
55 | */
56 | def withdraw(amount: Int): Boolean = {
57 | if (amount > 0 && amount <= _balance) {
58 | _balance -= amount
59 | true
60 | } else false
61 | }
62 | }
63 |
64 | object Account {
65 | val acc = new Account(0, new Customer, "01234567")
66 | acc.balance = 700
67 | acc.balance += 40
68 | }
--------------------------------------------------------------------------------
/src/oodetails/AssignmentOps.scala:
--------------------------------------------------------------------------------
1 | package oodetails
2 |
3 | object AssignmentOps {
4 | def main(args: Array[String]): Unit = {
5 | var v1 = new Vect2D_b(1, 2)
6 | val v2 = new Vect2D_b(2, 2)
7 | v1 += v2 // using v1 = v1.+(v2)
8 |
9 | val mv1 = new MutableVect2D_b(1, 2)
10 | val mv2 = new MutableVect2D_b(2, 2)
11 | mv1 += mv2 // using mv1.+=(mv2)
12 | }
13 | }
--------------------------------------------------------------------------------
/src/oodetails/MutableVect2D.scala:
--------------------------------------------------------------------------------
1 | package oodetails
2 |
3 | class MutableVect2D private(private[this] var _x: Double, private[this] var _y: Double) {
4 | def x = _x
5 | def y = _y
6 | def x_=(newX: Double): Unit = _x = newX
7 | def y_=(newY: Double): Unit = _y = newY
8 | def +=(mv: MutableVect2D): MutableVect2D = {
9 | _x += mv.x
10 | _y += mv.y
11 | this
12 | }
13 | def -=(mv: MutableVect2D): MutableVect2D = {
14 | _x -= mv.x
15 | _y -= mv.y
16 | this
17 | }
18 | def *=(c: Double): MutableVect2D = {
19 | _x *= c
20 | _y *= c
21 | this
22 | }
23 | def /=(c: Double): MutableVect2D = {
24 | _x /= c
25 | _y /= c
26 | this
27 | }
28 | def magnitude = math.sqrt(x * x + y * y)
29 | def apply(index:Int): Double = index match {
30 | case 0 => x
31 | case 1 => y
32 | case _ => throw new IndexOutOfBoundsException(s"2D vector indexed with $index.")
33 | }
34 | def update(index:Int, value:Double): Unit = index match {
35 | case 0 => x = value
36 | case 1 => y = value
37 | case _ => throw new IndexOutOfBoundsException(s"2D vector indexed with $index.")
38 | }
39 | }
40 |
41 | object MutableVect2D {
42 | def main(args:Array[String]):Unit = {
43 | val v1 = MutableVect2D(1, 2)
44 | val v2 = MutableVect2D(2, 2)
45 | v1 += v2
46 | println(v1.magnitude)
47 | v2.x = 3
48 | v2(0) = 99
49 | }
50 |
51 | def apply(x:Double, y:Double) = new MutableVect2D(x, y)
52 | }
--------------------------------------------------------------------------------
/src/oodetails/MutableVect2D_a.scala:
--------------------------------------------------------------------------------
1 | package oodetails
2 |
3 | /**
4 | * A basics 2D mutable vector.
5 | */
6 | class MutableVect2D_a(private var _x: Double, private var _y: Double) {
7 | def x = _x
8 | def y = _y
9 | def setX(newX: Double): Unit = _x = newX
10 | def setY(newY: Double): Unit = _y = newY
11 | def plus(mv: MutableVect2D_a): MutableVect2D_a = {
12 | _x += mv.x
13 | _y += mv.y
14 | this
15 | }
16 | def minus(mv: MutableVect2D_a): MutableVect2D_a = {
17 | _x -= mv.x
18 | _y -= mv.y
19 | this
20 | }
21 | def scale(c: Double): MutableVect2D_a = {
22 | _x *= c
23 | _y *= c
24 | this
25 | }
26 | def magnitude = math.sqrt(x * x + y * y)
27 | }
28 |
29 | object MutableVect2D_a {
30 | def main(args:Array[String]):Unit = {
31 | val v1 = new MutableVect2D_a(1, 2)
32 | val v2 = new MutableVect2D_a(2, 2)
33 | v1.plus(v2)
34 | println(v1.magnitude)
35 | }
36 | }
--------------------------------------------------------------------------------
/src/oodetails/MutableVect2D_b.scala:
--------------------------------------------------------------------------------
1 | package oodetails
2 |
3 | class MutableVect2D_b(private var _x: Double, private var _y: Double) {
4 | def x = _x
5 | def y = _y
6 | def setX(newX: Double): Unit = _x = newX
7 | def setY(newY: Double): Unit = _y = newY
8 | def +=(mv: MutableVect2D_b): MutableVect2D_b = {
9 | _x += mv.x
10 | _y += mv.y
11 | this
12 | }
13 | def -=(mv: MutableVect2D_b): MutableVect2D_b = {
14 | _x -= mv.x
15 | _y -= mv.y
16 | this
17 | }
18 | def *=(c: Double): MutableVect2D_b = {
19 | _x *= c
20 | _y *= c
21 | this
22 | }
23 | def /=(c: Double): MutableVect2D_b = {
24 | _x /= c
25 | _y /= c
26 | this
27 | }
28 | def magnitude = math.sqrt(x * x + y * y)
29 | }
30 |
31 | object MutableVect2D_b {
32 | def main(args:Array[String]):Unit = {
33 | val v1 = new MutableVect2D_b(1, 2)
34 | val v2 = new MutableVect2D_b(2, 2)
35 | v1 += v2
36 | println(v1.magnitude)
37 | v2.setX(3)
38 | }
39 | }
--------------------------------------------------------------------------------
/src/oodetails/StudentStuff.scala:
--------------------------------------------------------------------------------
1 | package oodetails
2 |
3 | case class Student(name: String, assignments: List[Int], tests: List[Int], quizzes: List[Int])
4 | case class Instructor(name: String, students: List[Student])
5 |
6 | object StudentStuff {
7 | def addGrade(s: Student, test: Int): Student = s.copy(tests = test :: s.tests)
8 |
9 | val participant: AnyRef = Instructor("Lewis", Nil)
10 |
11 | val assignmentAve = participant match {
12 | case Student(n, a, t, q) =>
13 | if (a.length == 0) 0.0 else a.sum.toDouble / a.length
14 | case Instructor(n, ss) =>
15 | val averages = for (Student(sn, a, t, q) <- ss) yield {
16 | if (a.length == 0) 0.0 else a.sum.toDouble / a.length
17 | }
18 | if (averages.length == 0) 0.0 else averages.sum.toDouble / averages.length
19 | }
20 |
21 | val assignmentAve2 = participant match {
22 | case stu: Student =>
23 | if (stu.assignments.length == 0) 0.0 else stu.assignments.sum.toDouble / stu.assignments.length
24 | case ins: Instructor =>
25 | val averages = for (stu: Student <- ins.students) yield {
26 | if (stu.assignments.length == 0) 0.0 else stu.assignments.sum.toDouble / stu.assignments.length
27 | }
28 | if (averages.length == 0) 0.0 else averages.sum.toDouble / averages.length
29 | }
30 |
31 | val Instructor(iname, Student(sname, a, firstTest :: otherTests, q) :: Nil) = participant
32 |
33 | }
--------------------------------------------------------------------------------
/src/oodetails/Vect2D.scala:
--------------------------------------------------------------------------------
1 | package oodetails
2 |
3 | class Vect2D private(val x: Double, val y: Double) {
4 | def +(v: Vect2D) = Vect2D(x + v.x, y + v.y)
5 | def -(v: Vect2D) = Vect2D(x - v.x, y - v.y)
6 | def *(c: Double) = Vect2D(x * c, y * c)
7 | def /(c: Double) = Vect2D(x / c, y / c)
8 | def magnitude = math.sqrt(x * x + y * y)
9 | def dot(v: Vect2D) = x * v.x + y * v.y
10 | def cross(v: Vect2D) = x * v.y - y * v.x
11 | def unary_-() = Vect2D(-x, -y)
12 | def apply(index:Int): Double = index match {
13 | case 0 => x
14 | case 1 => y
15 | case _ => throw new IndexOutOfBoundsException(s"2D vector indexed with $index.")
16 | }
17 | }
18 |
19 | object Vect2D {
20 | def main(args: Array[String]): Unit = {
21 | val v1 = Vect2D(1, 2)
22 | val v2 = Vect2D(2, 2)
23 | val v3 = -(v1 + v2)
24 | val v4 = v3 * 3
25 | println(v3.magnitude+" "+v4.magnitude)
26 | }
27 |
28 | def apply(x:Double, y:Double) = new Vect2D(x, y)
29 | }
--------------------------------------------------------------------------------
/src/oodetails/Vect2D_a.scala:
--------------------------------------------------------------------------------
1 | package oodetails
2 |
3 | /**
4 | * A basic 2D immutable vector.
5 | */
6 | class Vect2D_a(val x: Double, val y: Double) {
7 | def plus(v: Vect2D_a) = new Vect2D_a(x + v.x, y + v.y)
8 | def minus(v: Vect2D_a) = new Vect2D_a(x - v.x, y - v.y)
9 | def scale(c: Double) = new Vect2D_a(x * c, y * c)
10 | def magnitude = math.sqrt(x * x + y * y)
11 | }
12 |
13 | object Vect2D_a {
14 | def main(args: Array[String]): Unit = {
15 | val v1 = new Vect2D_a(1, 2)
16 | val v2 = new Vect2D_a(2, 2)
17 | val v3 = v1.plus(v2)
18 | println(v3.magnitude)
19 | }
20 | }
--------------------------------------------------------------------------------
/src/oodetails/Vect2D_b.scala:
--------------------------------------------------------------------------------
1 | package oodetails
2 |
3 | class Vect2D_b(val x: Double, val y: Double) {
4 | def +(v: Vect2D_b) = new Vect2D_b(x + v.x, y + v.y)
5 | def -(v: Vect2D_b) = new Vect2D_b(x - v.x, y - v.y)
6 | def *(c: Double) = new Vect2D_b(x * c, y * c)
7 | def /(c: Double) = new Vect2D_b(x / c, y / c)
8 | def magnitude = math.sqrt(x * x + y * y)
9 | def dot(v: Vect2D_b) = x * v.x + y * v.y
10 | def cross(v: Vect2D_b) = x * v.y - y * v.x
11 | def unary_-() = new Vect2D_b(-x, -y)
12 | }
13 |
14 | object Vect2D_b {
15 | def main(args: Array[String]): Unit = {
16 | val v1 = new Vect2D_b(1, 2)
17 | val v2 = new Vect2D_b(2, 2)
18 | val v3 = -(v1 + v2)
19 | val v4 = v3 * 3
20 | println(v3.magnitude+" "+v4.magnitude)
21 | }
22 | }
--------------------------------------------------------------------------------
/src/polymorphism/BasicAbstraction.scala:
--------------------------------------------------------------------------------
1 | package polymorphism
2 |
3 | import io.StdIn._
4 |
5 | object BasicAbstraction {
6 | def square(x: Double): Double = x * x
7 |
8 | def sumValues(n: Int): Double = {
9 | if (n < 1) 0.0 else readDouble() + sumValues(n - 1)
10 | }
11 |
12 | def multiplyValues(n: Int): Double = {
13 | if (n < 1) 1.0 else readDouble() * multiplyValues(n - 1)
14 | }
15 |
16 | def combineValues(n: Int, base: Double, op: (Double, Double) => Double): Double = {
17 | if (n < 1) base else op(readDouble(), combineValues(n - 1, base, op))
18 | }
19 |
20 | def main(args: Array[String]): Unit = {
21 | println(combineValues(5, Double.MaxValue, _ min _))
22 | }
23 | }
--------------------------------------------------------------------------------
/src/polymorphism/FruitFunctions.scala:
--------------------------------------------------------------------------------
1 | package polymorphism
2 |
3 | // Required to make things compile
4 | class Skin
5 |
6 | abstract class Fruit {
7 | def canEatSkin: Boolean
8 | def fractionalLiquidContent: Double
9 | def peel(): Skin
10 | }
11 |
12 | class Cherry extends Fruit {
13 | def canEatSkin: Boolean = true
14 | def fractionalLiquidContent: Double = 0.2
15 | def peel(): Skin = new Skin
16 | }
17 |
18 | // Required to make things compile
19 | class Blender {
20 | def +=(o: Any): Unit = ???
21 | def blend(): Unit = ???
22 | }
23 |
24 | object FruitFunctions {
25 | val blender = new Blender
26 | val juice = "Orange juice"
27 | val ice = "Ice"
28 |
29 | def makeBreakfastShake(fruit: Fruit): Unit = {
30 | if (!fruit.canEatSkin) {
31 | fruit.peel()
32 | }
33 | blender += fruit
34 | blender += juice
35 | if (fruit.fractionalLiquidContent < 0.3) blender += juice
36 | blender += ice
37 | blender.blend
38 | }
39 |
40 | def makeBreakfastShake(fruits: Array[Fruit]) {
41 | for (fruit <- fruits) {
42 | if (!fruit.canEatSkin) {
43 | fruit.peel
44 | }
45 | blender += fruit
46 | }
47 | blender += juice
48 | blender += ice
49 | blender.blend
50 | }
51 |
52 | def subCherries(bowl: Array[Fruit]) {
53 | if (!bowl.isEmpty) bowl(0) = new Cherry
54 | }
55 |
56 | def makeBreakfastShake2[A <: Fruit](fruits: Array[A]) {
57 | for (fruit <- fruits) {
58 | if (!fruit.canEatSkin) {
59 | fruit.peel
60 | }
61 | blender += fruit
62 | }
63 | blender += juice
64 | blender += ice
65 | blender.blend
66 | }
67 |
68 | def makeBreakfastShake(fruits: List[Fruit]) {
69 | for (fruit <- fruits) {
70 | if (!fruit.canEatSkin) {
71 | fruit.peel
72 | }
73 | blender += fruit
74 | }
75 | blender += juice
76 | blender += ice
77 | blender.blend
78 | }
79 |
80 | }
--------------------------------------------------------------------------------
/src/polymorphism/Person.scala:
--------------------------------------------------------------------------------
1 | package polymorphism
2 |
3 | trait Person {
4 | val name: String
5 | }
6 |
7 | trait Parent extends Person {
8 | def children: List[Person]
9 | }
10 |
11 | trait Female extends Person
12 |
13 | class Mother(val name: String) extends Parent with Female {
14 | override def children: List[Person] = ???
15 | }
--------------------------------------------------------------------------------
/src/polymorphism/Sorting.scala:
--------------------------------------------------------------------------------
1 | package polymorphism
2 |
3 | object Sorting {
4 | def bubbleSort(arr: Array[Double]): Unit = {
5 | for (i <- 0 until arr.length - 1; j <- 0 until arr.length - i - 1) {
6 | if (arr(j + 1) < arr(j)) {
7 | val tmp = arr(j)
8 | arr(j) = arr(j + 1)
9 | arr(j + 1) = tmp
10 | }
11 | }
12 | }
13 | }
--------------------------------------------------------------------------------
/src/polymorphism/Sorts.scala:
--------------------------------------------------------------------------------
1 | package polymorphism
2 |
3 | object Sorts {
4 | // def bubbleSort[A](arr: Array[A]): Unit = {
5 | // for (i <- 0 until arr.length - 1; j <- 0 until arr.length - i - 1) {
6 | // if (arr(j + 1) < arr(j)) { // Error: < not a member of type parameter A
7 | // val tmp = arr(j)
8 | // arr(j) = arr(j + 1)
9 | // arr(j + 1) = tmp
10 | // }
11 | // }
12 | // }
13 |
14 | def bubbleSort[A](a: Array[A])(lt: (A, A) => Boolean) {
15 | for (i <- 0 until a.length; j <- 0 until a.length - 1 - i) {
16 | if (lt(a(j + 1), a(j))) {
17 | val tmp = a(j)
18 | a(j) = a(j + 1)
19 | a(j + 1) = tmp
20 | }
21 | }
22 | }
23 |
24 | def bubbleSort[A <% Ordered[A]](a: Array[A]) {
25 | for (i <- 0 until a.length; j <- 0 until a.length - 1 - i) {
26 | if (a(j + 1) < a(j)) {
27 | val tmp = a(j)
28 | a(j) = a(j + 1)
29 | a(j + 1) = tmp
30 | }
31 | }
32 | }
33 |
34 | }
--------------------------------------------------------------------------------
/src/polymorphism/StreetLight.scala:
--------------------------------------------------------------------------------
1 | package polymorphism
2 |
3 | object StreetLightColor extends Enumeration {
4 | val Red, Green, Yellow = Value
5 | }
6 |
7 | class StreetLight(private var _color: StreetLightColor.Value) {
8 | def color = _color
9 |
10 | import StreetLightColor._
11 |
12 | def cycle: Unit = _color match {
13 | case Red => _color = Green
14 | case Green => _color = Yellow
15 | case Yellow => _color = Red
16 | }
17 | }
--------------------------------------------------------------------------------
/src/polymorphism/StringComparison.scala:
--------------------------------------------------------------------------------
1 | package polymorphism
2 |
3 | object StringComparison extends App {
4 |
5 | class CharInStrComp(val str: String) {
6 | def positionCompare(str2: String, index: Int): Int = {
7 | if (index >= str.length) {
8 | if (index >= str2.length) 0 else -1
9 | } else if (index >= str2.length) 1 else {
10 | str(index).compareTo(str2(index))
11 | }
12 | }
13 | }
14 |
15 | class CntCharInStrComp(s: String) extends CharInStrComp(s) {
16 | var cnt = 0
17 | override def positionCompare(str2: String, index: Int): Int = {
18 | cnt += 1
19 | super.positionCompare(str2, index)
20 | }
21 | }
22 |
23 | val csc = new CharInStrComp("Testi")
24 | println(csc.positionCompare("Testzng", 4))
25 | }
--------------------------------------------------------------------------------
/src/polymorphism/StructuralTypes.scala:
--------------------------------------------------------------------------------
1 | package polymorphism
2 |
3 | object StructuralTypes extends App {
4 | def structRead[A <: { def hasNextInt(): Boolean; def nextInt(): Int }](source: A): List[Int] = {
5 | var buf = List[Int]()
6 | while (source.hasNextInt) buf ::= source.nextInt
7 | buf.reverse
8 | }
9 | }
--------------------------------------------------------------------------------
/src/polymorphism/shape1/MutableRectangle.scala:
--------------------------------------------------------------------------------
1 | package polymorphism.shape1
2 |
3 | import scalafx.scene.canvas.GraphicsContext
4 |
5 | class MutableRectangle(var width: Double, var height: Double) extends Shape {
6 | override def area: Double = width * height
7 | override def perimeter: Double = 2.0 * (width + height)
8 | override def draw(gc: GraphicsContext): Unit = {
9 | gc.fillRect(0.0, 0.0, width, height)
10 | }
11 | }
--------------------------------------------------------------------------------
/src/polymorphism/shape1/MutableSquare.scala:
--------------------------------------------------------------------------------
1 | package polymorphism.shape1
2 |
3 | class MutableSquare(length: Double) extends MutableRectangle(length, length) {
4 | /*
5 | override def width_=(w: Double): Unit = { // ERROR: Can't override mutable variables.
6 | width = w
7 | height = w
8 | }
9 | override def height_=(h: Double): Unit = { // ERROR: Can't override mutable variables.
10 | height = h
11 | width = h
12 | }
13 | */
14 | }
--------------------------------------------------------------------------------
/src/polymorphism/shape1/Shape.scala:
--------------------------------------------------------------------------------
1 | package polymorphism.shape1
2 |
3 | import scalafx.scene.canvas.GraphicsContext
4 |
5 | class Shape {
6 | def area: Double = 0.0
7 | def perimeter: Double = 0.0
8 | def draw(gc: GraphicsContext): Unit = {}
9 | }
10 |
11 | class Rectangle(val width: Double, val height: Double) extends Shape {
12 | override def area: Double = width * height
13 | override def perimeter: Double = 2.0 * (width + height)
14 | override def draw(gc: GraphicsContext): Unit = {
15 | gc.fillRect(0, 0, width, height)
16 | }
17 | }
18 |
19 | class Circle(val radius: Double) extends Shape {
20 | override def area: Double = math.Pi * radius * radius
21 | override def perimeter: Double = 2.0 * math.Pi * radius
22 | override def draw(gc: GraphicsContext): Unit = {
23 | gc.fillOval(0, 0, radius, radius)
24 | }
25 | }
26 |
27 | class Square(length: Double) extends Rectangle(length, length)
--------------------------------------------------------------------------------
/src/polymorphism/shape1/ShapeFunctions.scala:
--------------------------------------------------------------------------------
1 | package polymorphism.shape1
2 |
3 | object ShapeFunctions {
4 | def areaPerimeterRatio(s: Shape): Double = {
5 | s.area / s.perimeter
6 | }
7 |
8 | val circleAPR = areaPerimeterRatio(new Circle(5))
9 | val rectAPR = areaPerimeterRatio(new Rectangle(4, 5))
10 |
11 | def adjustRectangle(r: MutableRectangle): Unit = {
12 | r.width = 20
13 | }
14 |
15 | val square = new MutableSquare(5)
16 | adjustRectangle(square)
17 |
18 | }
--------------------------------------------------------------------------------
/src/polymorphism/shape2/Shape.scala:
--------------------------------------------------------------------------------
1 | package polymorphism.shape2
2 |
3 | import scalafx.scene.paint.Color
4 | import scalafx.scene.canvas.GraphicsContext
5 |
6 | class Shape(private var color: Color) {
7 | def area: Double = 0.0
8 | def circumference: Double = 0.0
9 | def draw(gc: GraphicsContext): Unit = {}
10 | }
11 |
12 | class Rectangle(val width:Double,val height:Double,c:Color) extends Shape(c) {
13 | override def area:Double = width*height
14 | override def circumference:Double = 2.0*(width+height)
15 | override def draw(gc: GraphicsContext): Unit = {
16 | // gc.fill = color // ERROR: Can't get to the private color data member.
17 | gc.fillRect(0.0,0.0,width,height)
18 | }
19 | }
20 |
21 | class Circle(val radius:Double,c:Color) extends Shape(c) {
22 | override def area:Double = math.Pi*radius*radius
23 | override def circumference:Double = 2.0*math.Pi*radius
24 | override def draw(gc: GraphicsContext): Unit = {
25 | // gc.fill = color // ERROR: Can't get to the private color data member.
26 | gc.fillOval(0.0,0.0,2.0*radius,2.0*radius)
27 | }
28 | }
--------------------------------------------------------------------------------
/src/polymorphism/shape3/Shape.scala:
--------------------------------------------------------------------------------
1 | package polymorphism.shape3
2 |
3 | import scalafx.scene.paint.Color
4 | import scalafx.scene.canvas.GraphicsContext
5 |
6 | class Shape(protected var color: Color) {
7 | def area: Double = 0.0
8 | def circumference: Double = 0.0
9 | def draw(gc: GraphicsContext): Unit = {}
10 | }
11 |
12 | class Rectangle(val width:Double,val height:Double,c:Color) extends Shape(c) {
13 | override def area:Double = width*height
14 | override def circumference:Double = 2.0*(width+height)
15 | override def draw(gc: GraphicsContext): Unit = {
16 | gc.fill = color
17 | gc.fillRect(0.0,0.0,width,height)
18 | }
19 | }
20 |
21 | class Circle(val radius:Double,c:Color) extends Shape(c) {
22 | override def area:Double = math.Pi*radius*radius
23 | override def circumference:Double = 2.0*math.Pi*radius
24 | override def draw(gc: GraphicsContext): Unit = {
25 | gc.fill = color
26 | gc.fillOval(0.0,0.0,2.0*radius,2.0*radius)
27 | }
28 | }
--------------------------------------------------------------------------------
/src/polymorphism/shapeabstract/Shape.scala:
--------------------------------------------------------------------------------
1 | package polymorphism.shapeabstract
2 |
3 | import scalafx.scene.canvas.GraphicsContext
4 | import scalafx.scene.paint.Color
5 |
6 | abstract class Shape(private var color: Color) {
7 | def area: Double
8 | def perimeter: Double
9 | def draw(gc: GraphicsContext): Unit = {
10 | gc.fill = color
11 | }
12 | }
--------------------------------------------------------------------------------
/src/polymorphism/supershape/Rectangle.scala:
--------------------------------------------------------------------------------
1 | package polymorphism.supershape
2 |
3 | import scalafx.scene.canvas.GraphicsContext
4 | import scalafx.scene.paint.Color
5 |
6 | class Rectangle(val width: Double, val height: Double, c: Color) extends Shape(c) {
7 | override def area: Double = width * height
8 | override def perimeter: Double = 2.0 * (width + height)
9 | override def draw(g: GraphicsContext): Unit = {
10 | super.draw(g)
11 | g.fillRect(0.0, 0.0, width, height)
12 | }
13 | }
--------------------------------------------------------------------------------
/src/polymorphism/supershape/Shape.scala:
--------------------------------------------------------------------------------
1 | package polymorphism.supershape
2 |
3 | import scalafx.scene.canvas.GraphicsContext
4 | import scalafx.scene.paint.Color
5 |
6 | class Shape(private var color: Color) {
7 | def area: Double = 0.0
8 | def perimeter: Double = 0.0
9 | def draw(gc: GraphicsContext): Unit = {
10 | gc.fill = color
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/polymorphism/themepark/UseToD.scala:
--------------------------------------------------------------------------------
1 | package polymorphism.themepark
2 |
3 | object UseToD extends App {
4 | val riders1 = new ToDValues[Int]
5 | val riders2 = new ToDValues[Int]
6 | val worker1 = new ToDValues[String]
7 | val worker2 = new ToDValues[String]
8 |
9 | riders1(12) = 5
10 | riders1("8:24AM") = 10
11 | riders1(14) = 7
12 | riders2("2:13PM") = 8
13 |
14 | worker1(12) = "Kyle"
15 |
16 | val totalRiders = riders1.combine(riders2, (o1, o2) => (o1, o2) match {
17 | case (None, None) => None
18 | case (Some(a), None) => Some(a)
19 | case (None, Some(b)) => Some(b)
20 | case (Some(a), Some(b)) => Some(a + b)
21 | })
22 |
23 | println(riders1)
24 | println(totalRiders)
25 | }
--------------------------------------------------------------------------------
/src/priorityqueues/adt/PriorityQueue.scala:
--------------------------------------------------------------------------------
1 | package priorityqueues.adt
2 |
3 | /**
4 | * This trait defines a mutable Priority Queue ADT.
5 | * @tparam A the type of data stored
6 | */
7 | trait PriorityQueue[A] {
8 | /**
9 | * Add an item to the priority queue.
10 | * @param obj the item to add
11 | */
12 | def enqueue(obj: A): Unit
13 |
14 | /**
15 | * Remove the item that has the highest priority or, in the case of a tie,
16 | * has been on the longest.
17 | * @return the item that was removed
18 | */
19 | def dequeue(): A
20 |
21 | /**
22 | * Return the item that has the highest priority or, in the case of a tie,
23 | * has been on the longest without removing it.
24 | * @return the most recently added item
25 | */
26 | def peek: A
27 |
28 | /**
29 | * Tells whether this priority queue is empty.
30 | * @return true if there are no items on the priority queue, otherwise false.
31 | */
32 | def isEmpty: Boolean
33 | }
34 |
--------------------------------------------------------------------------------
/src/priorityqueues/adt/SortedListPQWithRemove.scala:
--------------------------------------------------------------------------------
1 | package priorityqueues.adt
2 |
3 | class SortedListPQWithRemove[A](comp: (A,A)=>Int) extends PriorityQueue[A] {
4 | private var default: A = _
5 | private class Node(var data: A, var prev: Node, var next: Node)
6 | private val end = new Node(default, null, null)
7 | end.next = end
8 | end.prev = end
9 |
10 | def enqueue(obj:A): Unit = {
11 | var rover = end.prev
12 | while (rover != end && comp(obj,rover.data) > 0) rover = rover.prev
13 | rover.next.prev = new Node(obj, rover, rover.next)
14 | rover.next = rover.next.prev
15 | }
16 |
17 | def dequeue(): A = {
18 | val ret = end.next.data
19 | end.next = end.next.next
20 | end.next.prev = end
21 | ret
22 | }
23 |
24 | def peek: A = end.next.data
25 |
26 | def isEmpty: Boolean = end.next==end
27 |
28 | def removeMatches(f: A => Boolean): Unit = {
29 | var rover = end.next
30 | while (rover != end) {
31 | if (f(rover.data)) {
32 | rover.prev.next = rover.next
33 | rover.next.prev = rover.prev
34 | }
35 | rover = rover.next
36 | }
37 | }
38 | }
--------------------------------------------------------------------------------
/src/priorityqueues/adt/SortedListPriorityQueue.scala:
--------------------------------------------------------------------------------
1 | package priorityqueues.adt
2 |
3 | class SortedListPriorityQueue[A](comp: (A,A)=>Int) extends PriorityQueue[A] {
4 | private var default: A = _
5 | private class Node(var data: A, var prev: Node, var next: Node)
6 | private val end = new Node(default, null, null)
7 | end.next = end
8 | end.prev = end
9 |
10 | def enqueue(obj:A): Unit = {
11 | var rover = end.prev
12 | while (rover != end && comp(obj,rover.data) > 0) rover = rover.prev
13 | rover.next.prev = new Node(obj, rover, rover.next)
14 | rover.next = rover.next.prev
15 | }
16 |
17 | def dequeue(): A = {
18 | val ret = end.next.data
19 | end.next = end.next.next
20 | end.next.prev = end
21 | ret
22 | }
23 |
24 | def peek: A = end.next.data
25 |
26 | def isEmpty: Boolean = end.next==end
27 | }
28 |
--------------------------------------------------------------------------------
/src/priorityqueues/drawing/CollaborationServer.scala:
--------------------------------------------------------------------------------
1 | package priorityqueues.drawing
2 |
3 | import java.rmi.RemoteException
4 | import java.rmi.server.UnicastRemoteObject
5 |
6 | import scala.collection.mutable
7 |
8 | @remote trait RemoteCollaborationServer {
9 | def joinCollaboration(col: RemoteCollaborator): (Array[RemoteCollaborator], Array[(String, Drawing)])
10 | def addDrawing(title: String, drawing: Drawing): Unit
11 | }
12 |
13 | class CollaborationServer extends UnicastRemoteObject with RemoteCollaborationServer {
14 | private val collaborators = mutable.Buffer[RemoteCollaborator]()
15 | private val drawings = mutable.Buffer[(String, Drawing)]()
16 |
17 | def joinCollaboration(col: RemoteCollaborator): (Array[RemoteCollaborator], Array[(String, Drawing)]) = {
18 | collaborators += col
19 | (collaborators.toArray, drawings.toArray)
20 | }
21 |
22 | def addDrawing(title: String, drawing: Drawing): Unit = {
23 | drawings += title -> drawing
24 | for (c <- collaborators) {
25 | try {
26 | c.addDrawing(title, drawing)
27 | } catch {
28 | case ex: RemoteException =>
29 | }
30 | }
31 | }
32 | }
--------------------------------------------------------------------------------
/src/priorityqueues/drawing/Commands.scala:
--------------------------------------------------------------------------------
1 | package priorityqueues.drawing
2 |
3 | import stackqueue.util.RPNCalc
4 | import scalafx.application.Platform
5 |
6 | object Commands {
7 | private val commands = Map[String, (String, Drawing) => Any](
8 | "add" -> ((rest, d) => rest.trim.split(" +").map(_.toInt).sum),
9 | "echo" -> ((rest, d) => rest.trim),
10 | "refresh" -> ((rest, d) => Platform.runLater { d.draw() } ),
11 | "rpn" -> ((rest,d) => (RPNCalc(rest.trim.split(" +"), d.vars))),
12 | "set" -> ((rest,d) => {
13 | val parts = rest.trim.split(" +")
14 | d.vars(parts(0)) = parts(1).toDouble
15 | parts(0)+" = "+parts(1)
16 | }),
17 | "freeze" -> ((rest,d) => Thread.sleep(rest.trim.toInt*1000)))
18 |
19 | def apply(input: String, drawing: Drawing): Any = {
20 | val spaceIndex = input.indexOf(' ')
21 | val (command, rest) = if (spaceIndex < 0) (input.toLowerCase(), "")
22 | else (input.take(spaceIndex).toLowerCase(), input.drop(spaceIndex))
23 | if (commands.contains(command)) commands(command)(rest, drawing) else "Not a valid command."
24 | }
25 | }
--------------------------------------------------------------------------------
/src/priorityqueues/drawing/Drawable.scala:
--------------------------------------------------------------------------------
1 | package priorityqueues.drawing
2 |
3 | import scalafx.scene.canvas.GraphicsContext
4 | import scalafx.scene.Node
5 |
6 | abstract class Drawable(val drawing: Drawing) extends Serializable {
7 | def draw(gc: GraphicsContext): Unit
8 | def propertiesPanel(): Node
9 | def toXML: xml.Node
10 | def advance(dt: Double): Unit = {}
11 | }
12 |
13 | object Drawable {
14 | def makeDrawable(n: xml.Node, d: Drawing): Drawable = {
15 | (n \ "@type").text match {
16 | case "rectangle" => DrawRectangle(n, d)
17 | case "text" => DrawText(n, d)
18 | case "transform" => DrawTransform(n, d)
19 | case "maze" => DrawMaze(n, d)
20 | case "mandelbrot" => DrawMandelbrot(n, d)
21 | case "julia" => DrawJulia(n, d)
22 | case "cellSim" => DrawCellSim(n, d)
23 | case "bouncingBalls" => DrawBouncingBalls(n, d)
24 | }
25 | }
26 | }
--------------------------------------------------------------------------------
/src/priorityqueues/drawing/Drawing.scala:
--------------------------------------------------------------------------------
1 | package priorityqueues.drawing
2 |
3 | import collection.mutable
4 | import scalafx.scene.canvas.GraphicsContext
5 | import scalafx.scene.control.TreeItem
6 | import scalafx.scene.paint.Color
7 |
8 | class Drawing(private[drawing] val vars: mutable.Map[String, Double]) extends Serializable {
9 | private var root = DrawTransform(this)
10 | @transient private var gc: GraphicsContext = null
11 |
12 | def graphicsContext_=(g: GraphicsContext): Unit = {
13 | gc = g
14 | }
15 |
16 | def graphicsContext = gc
17 |
18 | def draw(): Unit = {
19 | if (gc != null) {
20 | gc.fill = Color.White
21 | gc.fillRect(0, 0, 2000, 2000)
22 | root.draw(gc)
23 | }
24 | }
25 |
26 | def drawTo(tmpGC: GraphicsContext): Unit = {
27 | tmpGC.fill = Color.White
28 | tmpGC.fillRect(0, 0, 2000, 2000)
29 | root.draw(tmpGC)
30 | }
31 |
32 | def makeTree: TreeItem[Drawable] = {
33 | def helper(d: Drawable): TreeItem[Drawable] = d match {
34 | case dt: DrawTransform =>
35 | val item = new TreeItem(d)
36 | item.children = dt.children.map(c => helper(c))
37 | item
38 | case _ => new TreeItem(d)
39 | }
40 | helper(root)
41 | }
42 |
43 | def toXML: xml.Node = {
44 |
45 | { root.toXML }
46 | { for ((k, v) <- vars) yield }
47 |
48 | }
49 |
50 | def advance(dt: Double): Unit = {
51 | root.advance(dt)
52 | }
53 | }
54 |
55 | object Drawing {
56 | def apply(): Drawing = {
57 | new Drawing(mutable.Map())
58 | }
59 |
60 | def apply(n: xml.Node): Drawing = {
61 | val vars = mutable.Map((n \ "var").map(vnode => (vnode \ "@key").text -> (vnode \ "@value").text.toDouble): _*)
62 | val drawing = new Drawing(vars)
63 | drawing.root = DrawTransform(n \ "drawable", drawing)
64 | drawing
65 | }
66 |
67 | def colorToXML(color: Color): xml.Node = {
68 |
69 | }
70 |
71 | def xmlToColor(n: xml.NodeSeq): Color = {
72 | Color((n \ "@red").text.toDouble, (n \ "@green").text.toDouble, (n \ "@blue").text.toDouble, (n \ "@opacity").text.toDouble)
73 | }
74 | }
--------------------------------------------------------------------------------
/src/recursion/drawing/Clickable.scala:
--------------------------------------------------------------------------------
1 | package recursion.drawing
2 |
3 | import scalafx.scene.input.MouseEvent
4 |
5 | trait Clickable {
6 | def mouseEvent(me: MouseEvent):Unit
7 | }
--------------------------------------------------------------------------------
/src/recursion/drawing/CollaborationServer.scala:
--------------------------------------------------------------------------------
1 | package recursion.drawing
2 |
3 | import java.rmi.RemoteException
4 | import java.rmi.server.UnicastRemoteObject
5 |
6 | import scala.collection.mutable
7 |
8 | @remote trait RemoteCollaborationServer {
9 | def joinCollaboration(col: RemoteCollaborator): (Array[RemoteCollaborator], Array[(String, Drawing)])
10 | def addDrawing(title: String, drawing: Drawing): Unit
11 | }
12 |
13 | class CollaborationServer extends UnicastRemoteObject with RemoteCollaborationServer {
14 | private val collaborators = mutable.Buffer[RemoteCollaborator]()
15 | private val drawings = mutable.Buffer[(String, Drawing)]()
16 |
17 | def joinCollaboration(col: RemoteCollaborator): (Array[RemoteCollaborator], Array[(String, Drawing)]) = {
18 | collaborators += col
19 | (collaborators.toArray, drawings.toArray)
20 | }
21 |
22 | def addDrawing(title: String, drawing: Drawing): Unit = {
23 | drawings += title -> drawing
24 | for (c <- collaborators) {
25 | try {
26 | c.addDrawing(title, drawing)
27 | } catch {
28 | case ex: RemoteException =>
29 | }
30 | }
31 | }
32 | }
--------------------------------------------------------------------------------
/src/recursion/drawing/Commands.scala:
--------------------------------------------------------------------------------
1 | package recursion.drawing
2 |
3 | import stackqueue.util.RPNCalc
4 | import scalafx.application.Platform
5 |
6 | object Commands {
7 | private val commands = Map[String, (String, Drawing) => Any](
8 | "add" -> ((rest, d) => rest.trim.split(" +").map(_.toInt).sum),
9 | "echo" -> ((rest, d) => rest.trim),
10 | "refresh" -> ((rest, d) => Platform.runLater { d.draw() } ),
11 | "rpn" -> ((rest,d) => (RPNCalc(rest.trim.split(" +"), d.vars))),
12 | "set" -> ((rest,d) => {
13 | val parts = rest.trim.split(" +")
14 | d.vars(parts(0)) = parts(1).toDouble
15 | parts(0)+" = "+parts(1)
16 | }),
17 | "freeze" -> ((rest,d) => Thread.sleep(rest.trim.toInt*1000)))
18 |
19 | def apply(input: String, drawing: Drawing): Any = {
20 | val spaceIndex = input.indexOf(' ')
21 | val (command, rest) = if (spaceIndex < 0) (input.toLowerCase(), "")
22 | else (input.take(spaceIndex).toLowerCase(), input.drop(spaceIndex))
23 | if (commands.contains(command)) commands(command)(rest, drawing) else "Not a valid command."
24 | }
25 | }
--------------------------------------------------------------------------------
/src/recursion/drawing/Drawable.scala:
--------------------------------------------------------------------------------
1 | package recursion.drawing
2 |
3 | import scalafx.scene.canvas.GraphicsContext
4 | import scalafx.scene.Node
5 |
6 | abstract class Drawable(val drawing: Drawing) extends Serializable {
7 | def draw(gc: GraphicsContext): Unit
8 | def propertiesPanel(): Node
9 | def toXML: xml.Node
10 | def advance(dt: Double): Unit = {}
11 | }
12 |
13 | object Drawable {
14 | def makeDrawable(n: xml.Node, d: Drawing): Drawable = {
15 | (n \ "@type").text match {
16 | case "rectangle" => DrawRectangle(n, d)
17 | case "text" => DrawText(n, d)
18 | case "transform" => DrawTransform(n, d)
19 | case "maze" => DrawMaze(n, d)
20 | case "mandelbrot" => DrawMandelbrot(n, d)
21 | case "julia" => DrawJulia(n, d)
22 | case "cellSim" => DrawCellSim(n, d)
23 | case "bouncingBalls" => DrawBouncingBalls(n, d)
24 | case "graph" => DrawGraph(n, d)
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/src/recursion/drawing/Drawing.scala:
--------------------------------------------------------------------------------
1 | package recursion.drawing
2 |
3 | import collection.mutable
4 | import scalafx.scene.canvas.GraphicsContext
5 | import scalafx.scene.control.TreeItem
6 | import scalafx.scene.paint.Color
7 |
8 | class Drawing(private[drawing] val vars: mutable.Map[String, Double]) extends Serializable {
9 | private var root = DrawTransform(this)
10 | @transient private var gc: GraphicsContext = null
11 |
12 | def graphicsContext_=(g: GraphicsContext): Unit = {
13 | gc = g
14 | }
15 |
16 | def graphicsContext = gc
17 |
18 | def draw(): Unit = {
19 | if (gc != null) {
20 | gc.fill = Color.White
21 | gc.fillRect(0, 0, 2000, 2000)
22 | root.draw(gc)
23 | }
24 | }
25 |
26 | def drawTo(tmpGC: GraphicsContext): Unit = {
27 | tmpGC.fill = Color.White
28 | tmpGC.fillRect(0, 0, 2000, 2000)
29 | root.draw(tmpGC)
30 | }
31 |
32 | def makeTree: TreeItem[Drawable] = {
33 | def helper(d: Drawable): TreeItem[Drawable] = d match {
34 | case dt: DrawTransform =>
35 | val item = new TreeItem(d)
36 | item.children = dt.children.map(c => helper(c))
37 | item
38 | case _ => new TreeItem(d)
39 | }
40 | helper(root)
41 | }
42 |
43 | def toXML: xml.Node = {
44 |
45 | { root.toXML }
46 | { for ((k, v) <- vars) yield }
47 |
48 | }
49 |
50 | def advance(dt: Double): Unit = {
51 | root.advance(dt)
52 | }
53 | }
54 |
55 | object Drawing {
56 | def apply(): Drawing = {
57 | new Drawing(mutable.Map())
58 | }
59 |
60 | def apply(n: xml.Node): Drawing = {
61 | val vars = mutable.Map((n \ "var").map(vnode => (vnode \ "@key").text -> (vnode \ "@value").text.toDouble): _*)
62 | val drawing = new Drawing(vars)
63 | drawing.root = DrawTransform(n \ "drawable", drawing)
64 | drawing
65 | }
66 |
67 | def colorToXML(color: Color): xml.Node = {
68 |
69 | }
70 |
71 | def xmlToColor(n: xml.NodeSeq): Color = {
72 | Color((n \ "@red").text.toDouble, (n \ "@green").text.toDouble, (n \ "@blue").text.toDouble, (n \ "@opacity").text.toDouble)
73 | }
74 | }
--------------------------------------------------------------------------------
/src/recursion/util/Formula.scala:
--------------------------------------------------------------------------------
1 | package recursion.util
2 |
3 | object Formula {
4 | val ops = "+-*/".toSet
5 |
6 | def eval(form: String): Double = evalParse(form.filter(_ != ' '))
7 |
8 | private def evalParse(f: String): Double = {
9 | var opLoc = -1
10 | var parensCount = 0
11 | var i = f.length - 1
12 | while (i > 0) {
13 | if (f(i) == '(') parensCount += 1
14 | else if (f(i) == ')') parensCount -= 1
15 | else if (parensCount == 0 && (f(i) == '+' || f(i) == '-' && !ops(f(i - 1)))) {
16 | opLoc = i
17 | i = -1
18 | } else if (parensCount == 0 && opLoc == -1 && (f(i) == '*' || f(i) == '/')) {
19 | opLoc = i
20 | }
21 | i -= 1
22 | }
23 | if (opLoc < 0) {
24 | if (f(0) == '(') {
25 | evalParse(f.substring(1, f.length - 1))
26 | } else f.toDouble
27 | } else {
28 | f(opLoc) match {
29 | case '+' => evalParse(f.take(opLoc)) + evalParse(f.drop(opLoc + 1))
30 | case '-' => evalParse(f.take(opLoc)) - evalParse(f.drop(opLoc + 1))
31 | case '*' => evalParse(f.take(opLoc)) * evalParse(f.drop(opLoc + 1))
32 | case '/' => evalParse(f.take(opLoc)) / evalParse(f.drop(opLoc + 1))
33 | }
34 | }
35 | }
36 | }
--------------------------------------------------------------------------------
/src/regexparser/CodeSegments.scala:
--------------------------------------------------------------------------------
1 | package regexparser
2 |
3 | object CodeSegments extends App {
4 | val fileName = "lines.txt"
5 |
6 | val NumberedLine = """\s*(\d+)\.(.+)""".r
7 | val source = io.Source.fromFile(fileName)
8 | val lines = source.getLines
9 | val numberedLines = (for (NumberedLine(num, text) <- lines) yield {
10 | num -> text
11 | }).toMap
12 | source.close
13 | }
--------------------------------------------------------------------------------
/src/regexparser/drawing/Clickable.scala:
--------------------------------------------------------------------------------
1 | package regexparser.drawing
2 |
3 | import scalafx.scene.input.MouseEvent
4 |
5 | trait Clickable {
6 | def mouseEvent(me: MouseEvent):Unit
7 | }
--------------------------------------------------------------------------------
/src/regexparser/drawing/CollaborationServer.scala:
--------------------------------------------------------------------------------
1 | package regexparser.drawing
2 |
3 | import java.rmi.RemoteException
4 | import java.rmi.server.UnicastRemoteObject
5 |
6 | import scala.collection.mutable
7 |
8 | @remote trait RemoteCollaborationServer {
9 | def joinCollaboration(col: RemoteCollaborator): (Array[RemoteCollaborator], Array[(String, Drawing)])
10 | def addDrawing(title: String, drawing: Drawing): Unit
11 | }
12 |
13 | class CollaborationServer extends UnicastRemoteObject with RemoteCollaborationServer {
14 | private val collaborators = mutable.Buffer[RemoteCollaborator]()
15 | private val drawings = mutable.Buffer[(String, Drawing)]()
16 |
17 | def joinCollaboration(col: RemoteCollaborator): (Array[RemoteCollaborator], Array[(String, Drawing)]) = {
18 | collaborators += col
19 | (collaborators.toArray, drawings.toArray)
20 | }
21 |
22 | def addDrawing(title: String, drawing: Drawing): Unit = {
23 | drawings += title -> drawing
24 | for (c <- collaborators) {
25 | try {
26 | c.addDrawing(title, drawing)
27 | } catch {
28 | case ex: RemoteException =>
29 | }
30 | }
31 | }
32 | }
--------------------------------------------------------------------------------
/src/regexparser/drawing/Commands.scala:
--------------------------------------------------------------------------------
1 | package regexparser.drawing
2 |
3 | import stackqueue.util.RPNCalc
4 | import scalafx.application.Platform
5 | import regexparser.util.Formula
6 |
7 | object Commands {
8 | private val commands = Map[String, (String, Drawing) => Any](
9 | "add" -> ((rest, d) => rest.trim.split(" +").map(_.toInt).sum),
10 | "echo" -> ((rest, d) => rest.trim),
11 | "refresh" -> ((rest, d) => Platform.runLater { d.draw() } ),
12 | "rpn" -> ((rest,d) => (RPNCalc(rest.trim.split(" +"), d.vars))),
13 | "set" -> ((rest,d) => {
14 | val parts = rest.trim.split(" +")
15 | d.vars(parts(0)) = parts(1).toDouble
16 | parts(0)+" = "+parts(1)
17 | }),
18 | "freeze" -> ((rest,d) => Thread.sleep(rest.trim.toInt*1000)),
19 | "eval" -> ((rest, d) => Formula.eval(rest, d.vars)))
20 |
21 | val commandSplit = """\s*(\w+)(\s+(.*))?\s*""".r
22 |
23 | def apply(input:String, drawing:Drawing):Any = {
24 | val commandSplit(command, _, rest) = input
25 | if (commands.contains(command)) commands(command)(rest, drawing)
26 | else "Not a valid command."
27 | }
28 | }
--------------------------------------------------------------------------------
/src/regexparser/drawing/Drawable.scala:
--------------------------------------------------------------------------------
1 | package regexparser.drawing
2 |
3 | import scalafx.scene.canvas.GraphicsContext
4 | import scalafx.scene.Node
5 |
6 | abstract class Drawable(val drawing: Drawing) extends Serializable {
7 | def draw(gc: GraphicsContext): Unit
8 | def propertiesPanel(): Node
9 | def toXML: xml.Node
10 | def advance(dt: Double): Unit = {}
11 | }
12 |
13 | object Drawable {
14 | def makeDrawable(n: xml.Node, d: Drawing): Drawable = {
15 | (n \ "@type").text match {
16 | case "rectangle" => DrawRectangle(n, d)
17 | case "text" => DrawText(n, d)
18 | case "transform" => DrawTransform(n, d)
19 | case "maze" => DrawMaze(n, d)
20 | case "mandelbrot" => DrawMandelbrot(n, d)
21 | case "julia" => DrawJulia(n, d)
22 | case "cellSim" => DrawCellSim(n, d)
23 | case "bouncingBalls" => DrawBouncingBalls(n, d)
24 | case "graph" => DrawGraph(n, d)
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/src/regexparser/drawing/Drawing.scala:
--------------------------------------------------------------------------------
1 | package regexparser.drawing
2 |
3 | import collection.mutable
4 | import scalafx.scene.canvas.GraphicsContext
5 | import scalafx.scene.control.TreeItem
6 | import scalafx.scene.paint.Color
7 |
8 | class Drawing(private[drawing] val vars: mutable.Map[String, Double]) extends Serializable {
9 | private var root = DrawTransform(this)
10 | @transient private var gc: GraphicsContext = null
11 |
12 | def graphicsContext_=(g: GraphicsContext): Unit = {
13 | gc = g
14 | }
15 |
16 | def graphicsContext = gc
17 |
18 | def draw(): Unit = {
19 | if (gc != null) {
20 | gc.fill = Color.White
21 | gc.fillRect(0, 0, 2000, 2000)
22 | root.draw(gc)
23 | }
24 | }
25 |
26 | def drawTo(tmpGC: GraphicsContext): Unit = {
27 | tmpGC.fill = Color.White
28 | tmpGC.fillRect(0, 0, 2000, 2000)
29 | root.draw(tmpGC)
30 | }
31 |
32 | def makeTree: TreeItem[Drawable] = {
33 | def helper(d: Drawable): TreeItem[Drawable] = d match {
34 | case dt: DrawTransform =>
35 | val item = new TreeItem(d)
36 | item.children = dt.children.map(c => helper(c))
37 | item
38 | case _ => new TreeItem(d)
39 | }
40 | helper(root)
41 | }
42 |
43 | def toXML: xml.Node = {
44 |
45 | { root.toXML }
46 | { for ((k, v) <- vars) yield }
47 |
48 | }
49 |
50 | def advance(dt: Double): Unit = {
51 | root.advance(dt)
52 | }
53 | }
54 |
55 | object Drawing {
56 | def apply(): Drawing = {
57 | new Drawing(mutable.Map())
58 | }
59 |
60 | def apply(n: xml.Node): Drawing = {
61 | val vars = mutable.Map((n \ "var").map(vnode => (vnode \ "@key").text -> (vnode \ "@value").text.toDouble): _*)
62 | val drawing = new Drawing(vars)
63 | drawing.root = DrawTransform(n \ "drawable", drawing)
64 | drawing
65 | }
66 |
67 | def colorToXML(color: Color): xml.Node = {
68 |
69 | }
70 |
71 | def xmlToColor(n: xml.NodeSeq): Color = {
72 | Color((n \ "@red").text.toDouble, (n \ "@green").text.toDouble, (n \ "@blue").text.toDouble, (n \ "@opacity").text.toDouble)
73 | }
74 | }
--------------------------------------------------------------------------------
/src/scalalang/ShippingCalc.scala:
--------------------------------------------------------------------------------
1 | package scalalang
2 |
3 | import io.StdIn._
4 |
5 | object ShippingCalc {
6 | def main(args: Array[String]): Unit = {
7 | println("How many packages would you like to ship?") // This call to println sends text to standard output
8 | val numPackages = try {
9 | readInt()
10 | } catch {
11 | case _: NumberFormatException => 0 // If the user does not enter an integer value then the value will default to zero
12 | }
13 | var totalShippingCost = 0.0 // Be careful to initialize with a double value
14 | for (n <- 1 to numPackages) {
15 | println("What is the weight of package "+n+"?")
16 | totalShippingCost += calculateShippingCharge(readDouble())
17 | }
18 | println("Your total shipping charge is $"+totalShippingCost)
19 | }
20 |
21 | def calculateShippingCharge(weight: Double): Double = {
22 | if (weight <= 2) 2.5
23 | else if (weight <= 6) 4.0
24 | else if (weight <= 10) 5.0
25 | else 6.75
26 | } // end of calculateShippingCharge
27 | }
--------------------------------------------------------------------------------
/src/scalalang/ShippingCalcS.scala:
--------------------------------------------------------------------------------
1 | package scalalang
2 |
3 | import io.StdIn._
4 |
5 | object ShippingCalcS {
6 | def main(args: Array[String]): Unit = {
7 | println("How many packages would you like to ship?") // This call to println sends text to standard output
8 | val numPackages = try {
9 | readInt()
10 | } catch {
11 | case _: NumberFormatException => 0 // If the user does not enter an integer value then the value will default to zero
12 | }
13 | val shippingCharges = for (n <- 1 to numPackages) yield {
14 | println("What is the weight of package "+n+"?")
15 | calculateShippingCharge(readDouble())
16 | }
17 | println("Your total shipping charge is $"+shippingCharges.sum)
18 | }
19 |
20 | def calculateShippingCharge(weight: Double): Double = {
21 | if (weight <= 2) 2.5
22 | else if (weight <= 6) 4.0
23 | else if (weight <= 10) 5.0
24 | else 6.75
25 | } // end of calculateShippingCharge
26 | }
27 |
--------------------------------------------------------------------------------
/src/spatialtrees/adt/BruteForceNeighborVisitor.scala:
--------------------------------------------------------------------------------
1 | package spatialtrees.adt
2 |
3 | class BruteForceNeighborVisitor[A <% Int => Double](
4 | d: Int,
5 | val p: IndexedSeq[A]) extends NeighborVisitor[A](d) {
6 |
7 | def visitAllNeighbors(tDist: Double, visit: (A, A) => Unit): Unit = {
8 | for {
9 | i <- 0 until p.length
10 | pi = p(i)
11 | j <- i + 1 until p.length
12 | pj = p(j)
13 | if dist(pi, pj) <= tDist
14 | } visit(pi, pj)
15 | }
16 |
17 | def visitNeighbors(i: Int, tDist: Double, visit: (A, A) => Unit): Unit = {
18 | val pi = p(i)
19 | for {
20 | j <- 0 until p.length
21 | if j != i
22 | pj = p(j)
23 | if dist(pi, pj) <= tDist
24 | } visit(pi, pj)
25 | }
26 | }
--------------------------------------------------------------------------------
/src/spatialtrees/adt/NeighborVisitor.scala:
--------------------------------------------------------------------------------
1 | package spatialtrees.adt
2 |
3 | abstract class NeighborVisitor[A <% Int => Double](val dim: Int) {
4 | def visitAllNeighbors(tDist: Double, visit: (A, A) => Unit): Unit
5 | def visitNeighbors(i: Int, tDist: Double, visit: (A, A) => Unit): Unit
6 |
7 | var distCalcs = 0
8 | def dist[A <% Int => Double](p1: A, p2: A): Double = {
9 | distCalcs += 1
10 | math.sqrt((0 until dim).foldLeft(0.0)((d, i) => {
11 | val di = p1(i) - p2(i)
12 | d + di * di
13 | }))
14 | }
15 | }
--------------------------------------------------------------------------------
/src/stackqueue/adt/ArrayQueue.scala:
--------------------------------------------------------------------------------
1 | package stackqueue.adt
2 |
3 | import scala.reflect.ClassTag
4 |
5 | class ArrayQueue[A: ClassTag] extends Queue[A] {
6 | private var front, back = 0
7 | private var data = new Array[A](10)
8 |
9 | def enqueue(obj: A) {
10 | if ((back + 1) % data.length == front) {
11 | val tmp = new Array[A](data.length * 2)
12 | // Array.copy(data, 0, tmp, 0, data.length)
13 | for (i <- 0 until data.length - 1) tmp(i) = data((i + front) % data.length)
14 | front = 0
15 | back = data.length - 1
16 | data = tmp
17 | }
18 | data(back) = obj
19 | back = (back + 1) % data.length
20 | }
21 |
22 | def dequeue(): A = {
23 | assert(!isEmpty, "Dequeue called on an empty queue.")
24 | val ret = data(front)
25 | front = (front + 1) % data.length
26 | ret
27 | }
28 |
29 | def peek: A = data(front)
30 |
31 | def isEmpty: Boolean = front == back
32 | }
--------------------------------------------------------------------------------
/src/stackqueue/adt/ArrayStack.scala:
--------------------------------------------------------------------------------
1 | package stackqueue.adt
2 |
3 | import scala.reflect.ClassTag
4 |
5 | class ArrayStack[A: ClassTag] extends Stack[A] {
6 | private var top = 0
7 | private var data = new Array[A](10)
8 |
9 | def push(obj: A) {
10 | if (top >= data.length) {
11 | val tmp = new Array[A](data.length * 2)
12 | for (i <- 0 until data.length) tmp(i) = data(i)
13 | data = tmp
14 | }
15 | data(top) = obj
16 | top += 1
17 | }
18 |
19 | def pop(): A = {
20 | assert(!isEmpty, "Pop called on an empty stack.")
21 | top -= 1
22 | data(top)
23 | }
24 |
25 | def peek: A = data(top - 1)
26 |
27 | def isEmpty: Boolean = top == 0
28 | }
--------------------------------------------------------------------------------
/src/stackqueue/adt/Queue.scala:
--------------------------------------------------------------------------------
1 | package stackqueue.adt
2 |
3 | /**
4 | * This trait defines a mutable Queue ADT.
5 | * @tparam A the type of data stored
6 | */
7 | trait Queue[A] {
8 | /**
9 | * Add an item to the queue.
10 | * @param obj the item to add
11 | */
12 | def enqueue(obj: A)
13 |
14 | /**
15 | * Remove the item that has been on the longest.
16 | * @return the item that was removed
17 | */
18 | def dequeue(): A
19 |
20 | /**
21 | * Return the item that has been on the longest without removing it.
22 | * @return the most recently added item
23 | */
24 | def peek: A
25 |
26 | /**
27 | * Tells whether this queue is empty.
28 | * @return true if there are no items on the queue, otherwise false.
29 | */
30 | def isEmpty: Boolean
31 | }
--------------------------------------------------------------------------------
/src/stackqueue/adt/Stack.scala:
--------------------------------------------------------------------------------
1 | package stackqueue.adt
2 |
3 | /**
4 | * This trait defines a mutable Stack ADT.
5 | * @tparam A the type of data stored
6 | */
7 | trait Stack[A] {
8 | /**
9 | * Add an item to the stack.
10 | * @param obj the item to add
11 | */
12 | def push(obj: A)
13 |
14 | /**
15 | * Remove the most recently added item.
16 | * @return the item that was removed
17 | */
18 | def pop(): A
19 |
20 | /**
21 | * Return the most recently added item without removing it.
22 | * @return the most recently added item
23 | */
24 | def peek: A
25 |
26 | /**
27 | * Tells whether this stack is empty.
28 | * @return true if there are no items on the stack, otherwise false.
29 | */
30 | def isEmpty: Boolean
31 | }
--------------------------------------------------------------------------------
/src/stackqueue/drawing/Commands.scala:
--------------------------------------------------------------------------------
1 | package stackqueue.drawing
2 |
3 | import stackqueue.util.RPNCalc
4 |
5 | object Commands {
6 | private val commands = Map[String, (String, Drawing) => Any](
7 | "add" -> ((rest, d) => rest.trim.split(" +").map(_.toInt).sum),
8 | "echo" -> ((rest, d) => rest.trim),
9 | "refresh" -> ((rest, d) => d.draw()),
10 | "rpn" -> ((rest,d) => (RPNCalc(rest.trim.split(" +"), d.vars))),
11 | "set" -> ((rest,d) => {
12 | val parts = rest.trim.split(" +")
13 | d.vars(parts(0)) = parts(1).toDouble
14 | parts(0)+" = "+parts(1)
15 | }))
16 |
17 | def apply(input: String, drawing: Drawing): Any = {
18 | val spaceIndex = input.indexOf(' ')
19 | val (command, rest) = if (spaceIndex < 0) (input.toLowerCase(), "")
20 | else (input.take(spaceIndex).toLowerCase(), input.drop(spaceIndex))
21 | if (commands.contains(command)) commands(command)(rest, drawing) else "Not a valid command."
22 | }
23 | }
--------------------------------------------------------------------------------
/src/stackqueue/drawing/DrawRectangle.scala:
--------------------------------------------------------------------------------
1 | package stackqueue.drawing
2 |
3 | import scalafx.Includes._
4 | import scalafx.scene.canvas.GraphicsContext
5 | import scalafx.scene.paint.Color
6 | import scalafx.scene.Node
7 | import scalafx.scene.layout.VBox
8 | import scalafx.scene.control.TextField
9 | import scalafx.scene.control.ColorPicker
10 | import scalafx.event.ActionEvent
11 | import scalafx.scene.layout.Priority
12 |
13 | class DrawRectangle(
14 | d: Drawing,
15 | private var _x: Double,
16 | private var _y: Double,
17 | private var _width: Double,
18 | private var _height: Double,
19 | private var _color: Color) extends Drawable(d) {
20 |
21 | private var propPanel: Option[Node] = None
22 |
23 | override def toString = "Rectangle"
24 |
25 | def draw(gc: GraphicsContext): Unit = {
26 | gc.fill = _color
27 | gc.fillRect(_x, _y, _width, _height)
28 | }
29 |
30 | def propertiesPanel(): Node = {
31 | if (propPanel.isEmpty) {
32 | val panel = new VBox
33 | val xField = DrawingMain.labeledTextField("x", _x.toString, s => { _x = s.toDouble; drawing.draw() })
34 | val yField = DrawingMain.labeledTextField("y", _y.toString, s => { _y = s.toDouble; drawing.draw() })
35 | val widthField = DrawingMain.labeledTextField("width", _width.toString, s => { _width = s.toDouble; drawing.draw() })
36 | val heightField = DrawingMain.labeledTextField("height", _height.toString, s => { _height = s.toDouble; drawing.draw() })
37 | val colorPicker = new ColorPicker(_color)
38 | colorPicker.onAction = (ae: ActionEvent) => {
39 | _color = colorPicker.value.value
40 | drawing.draw()
41 | }
42 | panel.children = List(xField, yField, widthField, heightField, colorPicker)
43 | propPanel = Some(panel)
44 | }
45 | propPanel.get
46 | }
47 | }
--------------------------------------------------------------------------------
/src/stackqueue/drawing/DrawText.scala:
--------------------------------------------------------------------------------
1 | package stackqueue.drawing
2 |
3 | import scalafx.Includes._
4 | import scalafx.scene.canvas.GraphicsContext
5 | import scalafx.scene.paint.Color
6 | import scalafx.scene.Node
7 | import scalafx.scene.layout.VBox
8 | import scalafx.scene.control.ColorPicker
9 | import scalafx.event.ActionEvent
10 |
11 | class DrawText(
12 | d: Drawing,
13 | private var _x: Double,
14 | private var _y: Double,
15 | private var _text: String,
16 | private var _color: Color) extends Drawable(d) {
17 |
18 | private var propPanel: Option[Node] = None
19 |
20 | override def toString = "Text: "+_text
21 |
22 | def draw(gc: GraphicsContext): Unit = {
23 | gc.fill = _color
24 | gc.fillText(_text, _x, _y)
25 | }
26 |
27 | def propertiesPanel(): Node = {
28 | if (propPanel.isEmpty) {
29 | val panel = new VBox
30 | val textField = DrawingMain.labeledTextField("Text", _text, s => { _text = s; drawing.draw() })
31 | val xField = DrawingMain.labeledTextField("x", _x.toString, s => { _x = s.toDouble; drawing.draw() })
32 | val yField = DrawingMain.labeledTextField("y", _y.toString, s => { _y = s.toDouble; drawing.draw() })
33 | val colorPicker = new ColorPicker(_color)
34 | colorPicker.onAction = (ae: ActionEvent) => {
35 | _color = colorPicker.value.value
36 | drawing.draw()
37 | }
38 | panel.children = List(textField, xField, yField, colorPicker)
39 | propPanel = Some(panel)
40 | }
41 | propPanel.get
42 | }
43 | }
--------------------------------------------------------------------------------
/src/stackqueue/drawing/Drawable.scala:
--------------------------------------------------------------------------------
1 | package stackqueue.drawing
2 |
3 | import scalafx.scene.canvas.GraphicsContext
4 | import scalafx.scene.Node
5 |
6 | abstract class Drawable(val drawing: Drawing) {
7 | def draw(gc: GraphicsContext): Unit
8 | def propertiesPanel(): Node
9 | }
--------------------------------------------------------------------------------
/src/stackqueue/drawing/Drawing.scala:
--------------------------------------------------------------------------------
1 | package stackqueue.drawing
2 |
3 | import collection.mutable
4 | import scalafx.scene.canvas.GraphicsContext
5 | import scalafx.scene.control.TreeItem
6 | import scalafx.scene.paint.Color
7 |
8 | class Drawing(private var gc: GraphicsContext) {
9 | private var root = new DrawTransform(this)
10 |
11 | private[drawing] val vars = mutable.Map[String, Double]()
12 |
13 | def draw(): Unit = {
14 | gc.fill = Color.White
15 | gc.fillRect(0, 0, 2000, 2000)
16 | root.draw(gc)
17 | }
18 |
19 | def makeTree: TreeItem[Drawable] = {
20 | def helper(d: Drawable): TreeItem[Drawable] = d match {
21 | case dt: DrawTransform =>
22 | val item = new TreeItem(d)
23 | item.children = dt.children.map(c => helper(c))
24 | item
25 | case _ => new TreeItem(d)
26 | }
27 | helper(root)
28 | }
29 | }
--------------------------------------------------------------------------------
/src/stackqueue/util/RPNCalc.scala:
--------------------------------------------------------------------------------
1 | package stackqueue.util
2 |
3 | import stackqueue.adt.ArrayStack
4 |
5 | object RPNCalc {
6 | def apply(args: Seq[String], vars: collection.Map[String, Double]): Double = {
7 | val stack = new ArrayStack[Double]
8 | for (arg <- args; if (arg.nonEmpty)) arg match {
9 | case "+" => stack.push(stack.pop + stack.pop)
10 | case "*" => stack.push(stack.pop * stack.pop)
11 | case "-" =>
12 | val tmp = stack.pop
13 | stack.push(stack.pop - tmp)
14 | case "/" =>
15 | val tmp = stack.pop
16 | stack.push(stack.pop / tmp)
17 | case "sin" => stack.push(math.sin(stack.pop))
18 | case "cos" => stack.push(math.cos(stack.pop))
19 | case "tan" => stack.push(math.tan(stack.pop))
20 | case "sqrt" => stack.push(math.sqrt(stack.pop))
21 | case v if (v(0).isLetter) => stack.push(try { vars(v) } catch { case ex: NoSuchElementException => 0.0 })
22 | case x => stack.push(try { x.toDouble } catch { case ex: NoSuchElementException => 0.0 })
23 | }
24 | stack.pop
25 | }
26 | }
--------------------------------------------------------------------------------
/src/test/linkedlist/adt/TestImmutableSLList.scala:
--------------------------------------------------------------------------------
1 | package test.linkedlist.adt
2 |
3 | import org.junit._
4 | import org.junit.Assert._
5 | import linkedlist.adt.MyNil
6 | import linkedlist.adt.ImmutableSLList
7 |
8 | class TestImmutableSLList {
9 | @Test def nilIsEmpty: Unit = {
10 | assertTrue(MyNil.isEmpty)
11 | }
12 |
13 | @Test def buildCons: Unit = {
14 | val lst = 1 :: 2 :: 3 :: MyNil
15 | assertEquals(3, lst.length)
16 | assertEquals(1, lst.head)
17 | assertEquals(2, lst(1))
18 | assertEquals(3, lst(2))
19 | }
20 |
21 | @Test def buildApply: Unit = {
22 | val lst = ImmutableSLList(1, 2, 3)
23 | assertEquals(3, lst.length)
24 | assertEquals(1, lst.head)
25 | assertEquals(2, lst(1))
26 | assertEquals(3, lst(2))
27 | }
28 | }
--------------------------------------------------------------------------------
/src/test/linkedlist/adt/TestListQueue.scala:
--------------------------------------------------------------------------------
1 | package test.linkedlist.adt
2 |
3 | import org.junit._
4 | import org.junit.Assert._
5 | import linkedlist.adt.ListQueue
6 | import linkedlist.adt.Queue
7 |
8 | class TestListQueue {
9 | var queue: Queue[Int] = null
10 |
11 | @Before def initStack {
12 | queue = new ListQueue[Int]
13 | }
14 |
15 | @Test def emptyOnCreate {
16 | assertTrue(queue.isEmpty)
17 | }
18 |
19 | @Test def nonEmptyOnEnqueue {
20 | queue.enqueue(5)
21 | assertFalse(queue.isEmpty)
22 | }
23 |
24 | @Test def enqueueDequeue {
25 | queue.enqueue(5)
26 | assertEquals(5, queue.dequeue)
27 | }
28 |
29 | @Test def enqueueDequeueEnqueueDequeue {
30 | queue.enqueue(5)
31 | assertEquals(5, queue.dequeue)
32 | queue.enqueue(3)
33 | assertEquals(3, queue.dequeue)
34 | }
35 |
36 | @Test def enqueueEnqueueDequeueDequeue {
37 | queue.enqueue(5)
38 | queue.enqueue(3)
39 | assertEquals(5, queue.dequeue)
40 | assertEquals(3, queue.dequeue)
41 | }
42 |
43 | @Test def enqueue100Dequeue100 {
44 | val nums = Array.fill(100)(util.Random.nextInt)
45 | nums.foreach(queue.enqueue(_))
46 | nums.foreach(assertEquals(_, queue.dequeue))
47 | }
48 | }
--------------------------------------------------------------------------------
/src/test/linkedlist/adt/TestListStack.scala:
--------------------------------------------------------------------------------
1 | package test.linkedlist.adt
2 |
3 | import org.junit._
4 | import org.junit.Assert._
5 | import linkedlist.adt.ListStack
6 | import linkedlist.adt.Stack
7 |
8 | class TestListStack {
9 | var stack: Stack[Int] = null
10 |
11 | @Before def initStack {
12 | stack = new ListStack[Int]
13 | }
14 |
15 | @Test def emptyOnCreate {
16 | assertTrue(stack.isEmpty)
17 | }
18 |
19 | @Test def nonEmptyOnPush {
20 | stack.push(5)
21 | assertFalse(stack.isEmpty)
22 | }
23 |
24 | @Test def pushPop {
25 | stack.push(5)
26 | assertEquals(5, stack.pop)
27 | }
28 |
29 | @Test def pushPopPushPop {
30 | stack.push(5)
31 | assertEquals(5, stack.pop)
32 | stack.push(3)
33 | assertEquals(3, stack.pop)
34 | }
35 |
36 | @Test def pushPushPopPop {
37 | stack.push(5)
38 | stack.push(3)
39 | assertEquals(3, stack.pop)
40 | assertEquals(5, stack.pop)
41 | }
42 |
43 | @Test def push100Pop100 {
44 | val nums = Array.fill(100)(util.Random.nextInt)
45 | nums.foreach(stack.push(_))
46 | nums.reverse.foreach(assertEquals(_, stack.pop))
47 | }
48 | }
--------------------------------------------------------------------------------
/src/test/linkedlist/adt/TestMutableDLList.scala:
--------------------------------------------------------------------------------
1 | package test.linkedlist.adt
2 |
3 | import org.junit._
4 | import org.junit.Assert._
5 | import linkedlist.adt.MutableDLList
6 |
7 | class TestMutableDLList {
8 | var list: MutableDLList[Int] = null
9 |
10 | @Before def setup {
11 | list = new MutableDLList[Int]
12 | }
13 |
14 | @Test def startEmpty {
15 | assertTrue(list.isEmpty)
16 | }
17 |
18 | @Test def appendOne {
19 | list += 10
20 | assertFalse(list.isEmpty)
21 | assertEquals(1, list.length)
22 | assertEquals(10, list(0))
23 | }
24 |
25 | @Test def prependOne {
26 | 10 +=: list
27 | assertFalse(list.isEmpty)
28 | assertEquals(1, list.length)
29 | assertEquals(10, list(0))
30 | }
31 |
32 | @Test def appendOnePrependOne {
33 | list += 5
34 | 10 +=: list
35 | assertFalse(list.isEmpty)
36 | assertEquals(2, list.length)
37 | assertEquals(10, list(0))
38 | assertEquals(5, list(1))
39 | }
40 |
41 | @Test def insertList {
42 | list += 5 += 10
43 | list.insertAll(0, List(1, 2, 3))
44 | for ((e, a) <- List(1, 2, 3, 5, 10).zip(list)) {
45 | assertEquals(e, a)
46 | }
47 | }
48 |
49 | @Test def insertListRemove {
50 | list += 5 += 10
51 | list.insertAll(0, List(1, 2, 3))
52 | assertEquals(3, list.remove(2))
53 | for ((e, a) <- List(1, 2, 5, 10).zip(list)) {
54 | assertEquals(e, a)
55 | }
56 | }
57 | }
--------------------------------------------------------------------------------
/src/test/linkedlist/adt/TestMutableSLList.scala:
--------------------------------------------------------------------------------
1 | package test.linkedlist.adt
2 |
3 | import org.junit._
4 | import org.junit.Assert._
5 | import linkedlist.adt.MutableSLList
6 |
7 | class TestMutableSLList {
8 | var list: MutableSLList[Int] = null
9 |
10 | @Before def setup {
11 | list = new MutableSLList[Int]
12 | }
13 |
14 | @Test def startEmpty {
15 | assertTrue(list.isEmpty)
16 | }
17 |
18 | @Test def appendOne {
19 | list += 10
20 | assertFalse(list.isEmpty)
21 | assertEquals(1, list.length)
22 | assertEquals(10, list(0))
23 | }
24 |
25 | @Test def prependOne {
26 | 10 +=: list
27 | assertFalse(list.isEmpty)
28 | assertEquals(1, list.length)
29 | assertEquals(10, list(0))
30 | }
31 |
32 | @Test def appendOnePrependOne {
33 | list += 5
34 | 10 +=: list
35 | assertFalse(list.isEmpty)
36 | assertEquals(2, list.length)
37 | assertEquals(10, list(0))
38 | assertEquals(5, list(1))
39 | }
40 |
41 | @Test def insertList {
42 | list += 5 += 10
43 | list.insertAll(0, List(1, 2, 3))
44 | for ((e, a) <- List(1, 2, 3, 5, 10).zip(list)) {
45 | assertEquals(e, a)
46 | }
47 | }
48 |
49 | @Test def insertListRemove {
50 | list += 5 += 10
51 | list.insertAll(0, List(1, 2, 3))
52 | assertEquals(3, list.remove(2))
53 | for ((e, a) <- List(1, 2, 5, 10).zip(list)) {
54 | assertEquals(e, a)
55 | }
56 | }
57 | }
--------------------------------------------------------------------------------
/src/test/linkedlist/adt/TestSinglyLinkedList.scala:
--------------------------------------------------------------------------------
1 | package test.linkedlist.adt
2 |
3 | import org.junit._
4 | import org.junit.Assert._
5 | import linkedlist.adt.SinglyLinkedList
6 |
7 | class TestSinglyLinkedList {
8 | var list: SinglyLinkedList[Int] = null
9 |
10 | @Before def setup: Unit = {
11 | list = new SinglyLinkedList[Int]
12 | }
13 |
14 | @Test def appendOne: Unit = {
15 | list.insert(0, 10)
16 | assertEquals(10, list(0))
17 | }
18 |
19 | @Test def appendTwo: Unit = {
20 | list.insert(0, 10)
21 | list.insert(0, 20)
22 | assertEquals(20, list(0))
23 | assertEquals(10, list(1))
24 | }
25 |
26 | @Test def appendTwoB: Unit = {
27 | list.insert(0, 10)
28 | list.insert(1, 20)
29 | assertEquals(10, list(0))
30 | assertEquals(20, list(1))
31 | }
32 |
33 | @Test def appendTwoUpdate: Unit = {
34 | list.insert(0, 10)
35 | list.insert(0, 20)
36 | list(0) = 5
37 | list(1) = 8
38 | assertEquals(5, list(0))
39 | assertEquals(8, list(1))
40 | }
41 |
42 | @Test def appendRemove: Unit = {
43 | list.insert(0, 5)
44 | list.insert(1, 10)
45 | list.insert(2, 15)
46 | list.insert(3, 20)
47 | assertEquals(5, list(0))
48 | assertEquals(10, list(1))
49 | assertEquals(15, list(2))
50 | assertEquals(20, list(3))
51 | list.remove(2)
52 | assertEquals(5, list(0))
53 | assertEquals(10, list(1))
54 | assertEquals(20, list(2))
55 | list.remove(0)
56 | assertEquals(10, list(0))
57 | assertEquals(20, list(1))
58 | }
59 | }
--------------------------------------------------------------------------------
/src/test/priorityqueues/adt/TestSortedListPriorityQueue.scala:
--------------------------------------------------------------------------------
1 | package test.priorityqueues.adt
2 |
3 | import org.junit.Assert.assertEquals
4 | import org.junit.Assert.assertFalse
5 | import org.junit.Assert.assertTrue
6 | import org.junit.Before
7 | import org.junit.Test
8 |
9 | import priorityqueues.adt.PriorityQueue
10 | import priorityqueues.adt.SortedListPriorityQueue
11 |
12 | class TestSortedListPriorityQueue {
13 | var queue:PriorityQueue[Int] = null
14 |
15 | @Before def initQueue {
16 | queue = new SortedListPriorityQueue[Int]((a,b) => a.compareTo(b))
17 | }
18 |
19 | @Test def emptyOnCreate {
20 | assertTrue(queue.isEmpty)
21 | }
22 |
23 | @Test def nonEmptyOnEnqueue {
24 | queue.enqueue(5)
25 | assertFalse(queue.isEmpty)
26 | }
27 |
28 | @Test def enqueueDequeue {
29 | queue.enqueue(5)
30 | assertEquals(5,queue.dequeue)
31 | }
32 |
33 | @Test def enqueueDequeueEnqueueDequeue {
34 | queue.enqueue(5)
35 | assertEquals(5,queue.dequeue)
36 | queue.enqueue(3)
37 | assertEquals(3,queue.dequeue)
38 | }
39 |
40 | @Test def enqueueEnqueueDequeueDequeue {
41 | queue.enqueue(5)
42 | queue.enqueue(3)
43 | assertEquals(5,queue.dequeue)
44 | assertEquals(3,queue.dequeue)
45 | }
46 |
47 | @Test def enqueue100Dequeue100 {
48 | val nums = Array.fill(100)(util.Random.nextInt)
49 | nums.foreach(queue.enqueue)
50 | nums.sorted.reverse.foreach(assertEquals(_,queue.dequeue))
51 | }
52 | }
--------------------------------------------------------------------------------
/src/test/stackqueue/AllTests.scala:
--------------------------------------------------------------------------------
1 | package test.stackqueue
2 |
3 | import org.junit.runner.RunWith
4 | import org.junit.runners.Suite
5 |
6 | @RunWith(classOf[Suite])
7 | @Suite.SuiteClasses(Array(
8 | classOf[test.stackqueue.adt.TestArrayStack],
9 | classOf[test.stackqueue.adt.TestArrayQueue],
10 | classOf[test.stackqueue.util.TestRPNCalc]))
11 | class AllTests {}
--------------------------------------------------------------------------------
/src/test/stackqueue/adt/TestArrayQueue.scala:
--------------------------------------------------------------------------------
1 | package test.stackqueue.adt
2 |
3 | import org.junit._
4 | import org.junit.Assert._
5 | import stackqueue.adt._
6 |
7 | class TestArrayQueue {
8 | var queue: Queue[Int] = null
9 |
10 | @Before def initQueue {
11 | queue = new ArrayQueue[Int]
12 | }
13 |
14 | @Test def emptyOnCreate {
15 | assertTrue(queue.isEmpty)
16 | }
17 |
18 | @Test def nonEmptyOnEnqueue {
19 | queue.enqueue(5)
20 | assertFalse(queue.isEmpty)
21 | }
22 |
23 | @Test def enqueueDequeue {
24 | queue.enqueue(5)
25 | assertEquals(5, queue.dequeue)
26 | }
27 |
28 | @Test def enqueueDequeueEnqueueDequeue {
29 | queue.enqueue(5)
30 | assertEquals(5, queue.dequeue)
31 | queue.enqueue(3)
32 | assertEquals(3, queue.dequeue)
33 | }
34 |
35 | @Test def enqueueEnqueueDequeueDequeue {
36 | queue.enqueue(5)
37 | queue.enqueue(3)
38 | assertEquals(5, queue.dequeue)
39 | assertEquals(3, queue.dequeue)
40 | }
41 |
42 | @Test def enqueue100Dequeue100 {
43 | val nums = Array.fill(100)(util.Random.nextInt)
44 | nums.foreach(queue.enqueue(_))
45 | nums.foreach(assertEquals(_, queue.dequeue))
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/test/stackqueue/adt/TestArrayStack.scala:
--------------------------------------------------------------------------------
1 | package test.stackqueue.adt
2 |
3 | import org.junit._
4 | import org.junit.Assert._
5 | import stackqueue.adt._
6 |
7 | class TestArrayStack {
8 | var stack: Stack[Int] = null
9 |
10 | @Before def initStack {
11 | stack = new ArrayStack[Int]
12 | }
13 |
14 | @Test def emptyOnCreate {
15 | assertTrue(stack.isEmpty)
16 | }
17 |
18 | @Test def nonEmptyOnPush {
19 | stack.push(5)
20 | assertFalse(stack.isEmpty)
21 | }
22 |
23 | @Test def pushPop {
24 | stack.push(5)
25 | assertEquals(5, stack.pop)
26 | }
27 |
28 | @Test def pushPopPushPop {
29 | stack.push(5)
30 | assertEquals(5, stack.pop)
31 | stack.push(3)
32 | assertEquals(3, stack.pop)
33 | }
34 |
35 | @Test def pushPushPopPop {
36 | stack.push(5)
37 | stack.push(3)
38 | assertEquals(3, stack.pop)
39 | assertEquals(5, stack.pop)
40 | }
41 |
42 | @Test def push100Pop100 {
43 | val nums = Array.fill(100)(util.Random.nextInt)
44 | nums.foreach(stack.push(_))
45 | nums.reverse.foreach(assertEquals(_, stack.pop))
46 | }
47 | }
--------------------------------------------------------------------------------
/src/test/stackqueue/util/TestRPNCalc.scala:
--------------------------------------------------------------------------------
1 | package test.stackqueue.util
2 |
3 | import org.junit._
4 | import org.junit.Assert._
5 | import stackqueue.util.RPNCalc
6 |
7 | class TestRPNCalc {
8 | @Test def basicOps {
9 | assertEquals(5, RPNCalc("2 3 +".split(" "), null), 0.0)
10 | assertEquals(6, RPNCalc("2 3 *".split(" "), null), 0.0)
11 | assertEquals(3, RPNCalc("6 2 /".split(" "), null), 0.0)
12 | assertEquals(1, RPNCalc("3 2 -".split(" "), null), 0.0)
13 | }
14 |
15 | @Test def twoOps {
16 | assertEquals(20, RPNCalc("2 3 + 4 *".split(" "), null), 0.0)
17 | assertEquals(3, RPNCalc("2 3 * 3 -".split(" "), null), 0.0)
18 | assertEquals(5, RPNCalc("6 2 / 2 +".split(" "), null), 0.0)
19 | assertEquals(0.25, RPNCalc("3 2 - 4 /".split(" "), null), 0.0)
20 | }
21 |
22 | @Test def vars {
23 | val v = Map("x" -> 3.0, "y" -> 2.0)
24 | assertEquals(20, RPNCalc("2 x + 4 *".split(" "), v), 0.0)
25 | assertEquals(3, RPNCalc("y 3 * x -".split(" "), v), 0.0)
26 | assertEquals(5, RPNCalc("6 2 / y +".split(" "), v), 0.0)
27 | assertEquals(0.25, RPNCalc("x y - 4 /".split(" "), v), 0.0)
28 | }
29 |
30 | @Test def specials {
31 | val v = Map("pi" -> 3.14159, "x" -> 3.0, "y" -> 2.0)
32 | assertEquals(0, RPNCalc("pi cos 1 +".split(" "), v), 1e-8)
33 | assertEquals(math.sqrt(2) + 3, RPNCalc("y sqrt x +".split(" "), v), 1e-8)
34 | assertEquals(1, RPNCalc("pi 2 / sin".split(" "), v), 1e-8)
35 | assertEquals(0.0, RPNCalc("x y y 2 / + - tan".split(" "), v), 1e-8)
36 | }
37 | }
--------------------------------------------------------------------------------
/src/trees/drawing/Clickable.scala:
--------------------------------------------------------------------------------
1 | package trees.drawing
2 |
3 | import scalafx.scene.input.MouseEvent
4 |
5 | trait Clickable {
6 | def mouseEvent(me: MouseEvent):Unit
7 | }
--------------------------------------------------------------------------------
/src/trees/drawing/CollaborationServer.scala:
--------------------------------------------------------------------------------
1 | package trees.drawing
2 |
3 | import java.rmi.RemoteException
4 | import java.rmi.server.UnicastRemoteObject
5 |
6 | import scala.collection.mutable
7 |
8 | @remote trait RemoteCollaborationServer {
9 | def joinCollaboration(col: RemoteCollaborator): (Array[RemoteCollaborator], Array[(String, Drawing)])
10 | def addDrawing(title: String, drawing: Drawing): Unit
11 | }
12 |
13 | class CollaborationServer extends UnicastRemoteObject with RemoteCollaborationServer {
14 | private val collaborators = mutable.Buffer[RemoteCollaborator]()
15 | private val drawings = mutable.Buffer[(String, Drawing)]()
16 |
17 | def joinCollaboration(col: RemoteCollaborator): (Array[RemoteCollaborator], Array[(String, Drawing)]) = {
18 | collaborators += col
19 | (collaborators.toArray, drawings.toArray)
20 | }
21 |
22 | def addDrawing(title: String, drawing: Drawing): Unit = {
23 | drawings += title -> drawing
24 | for (c <- collaborators) {
25 | try {
26 | c.addDrawing(title, drawing)
27 | } catch {
28 | case ex: RemoteException =>
29 | }
30 | }
31 | }
32 | }
--------------------------------------------------------------------------------
/src/trees/drawing/Commands.scala:
--------------------------------------------------------------------------------
1 | package trees.drawing
2 |
3 | import stackqueue.util.RPNCalc
4 | import scalafx.application.Platform
5 |
6 | object Commands {
7 | private val commands = Map[String, (String, Drawing) => Any](
8 | "add" -> ((rest, d) => rest.trim.split(" +").map(_.toInt).sum),
9 | "echo" -> ((rest, d) => rest.trim),
10 | "refresh" -> ((rest, d) => Platform.runLater { d.draw() } ),
11 | "rpn" -> ((rest,d) => (RPNCalc(rest.trim.split(" +"), d.vars))),
12 | "set" -> ((rest,d) => {
13 | val parts = rest.trim.split(" +")
14 | d.vars(parts(0)) = parts(1).toDouble
15 | parts(0)+" = "+parts(1)
16 | }),
17 | "freeze" -> ((rest,d) => Thread.sleep(rest.trim.toInt*1000)))
18 |
19 | def apply(input: String, drawing: Drawing): Any = {
20 | val spaceIndex = input.indexOf(' ')
21 | val (command, rest) = if (spaceIndex < 0) (input.toLowerCase(), "")
22 | else (input.take(spaceIndex).toLowerCase(), input.drop(spaceIndex))
23 | if (commands.contains(command)) commands(command)(rest, drawing) else "Not a valid command."
24 | }
25 | }
--------------------------------------------------------------------------------
/src/trees/drawing/Drawable.scala:
--------------------------------------------------------------------------------
1 | package trees.drawing
2 |
3 | import scalafx.scene.canvas.GraphicsContext
4 | import scalafx.scene.Node
5 |
6 | abstract class Drawable(val drawing: Drawing) extends Serializable {
7 | def draw(gc: GraphicsContext): Unit
8 | def propertiesPanel(): Node
9 | def toXML: xml.Node
10 | def advance(dt: Double): Unit = {}
11 | }
12 |
13 | object Drawable {
14 | def makeDrawable(n: xml.Node, d: Drawing): Drawable = {
15 | (n \ "@type").text match {
16 | case "rectangle" => DrawRectangle(n, d)
17 | case "text" => DrawText(n, d)
18 | case "transform" => DrawTransform(n, d)
19 | case "maze" => DrawMaze(n, d)
20 | case "mandelbrot" => DrawMandelbrot(n, d)
21 | case "julia" => DrawJulia(n, d)
22 | case "cellSim" => DrawCellSim(n, d)
23 | case "bouncingBalls" => DrawBouncingBalls(n, d)
24 | case "graph" => DrawGraph(n, d)
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/src/trees/drawing/Drawing.scala:
--------------------------------------------------------------------------------
1 | package trees.drawing
2 |
3 | import collection.mutable
4 | import scalafx.scene.canvas.GraphicsContext
5 | import scalafx.scene.control.TreeItem
6 | import scalafx.scene.paint.Color
7 |
8 | class Drawing(private[drawing] val vars: mutable.Map[String, Double]) extends Serializable {
9 | private var root = DrawTransform(this)
10 | @transient private var gc: GraphicsContext = null
11 |
12 | def graphicsContext_=(g: GraphicsContext): Unit = {
13 | gc = g
14 | }
15 |
16 | def graphicsContext = gc
17 |
18 | def draw(): Unit = {
19 | if (gc != null) {
20 | gc.fill = Color.White
21 | gc.fillRect(0, 0, 2000, 2000)
22 | root.draw(gc)
23 | }
24 | }
25 |
26 | def drawTo(tmpGC: GraphicsContext): Unit = {
27 | tmpGC.fill = Color.White
28 | tmpGC.fillRect(0, 0, 2000, 2000)
29 | root.draw(tmpGC)
30 | }
31 |
32 | def makeTree: TreeItem[Drawable] = {
33 | def helper(d: Drawable): TreeItem[Drawable] = d match {
34 | case dt: DrawTransform =>
35 | val item = new TreeItem(d)
36 | item.children = dt.children.map(c => helper(c))
37 | item
38 | case _ => new TreeItem(d)
39 | }
40 | helper(root)
41 | }
42 |
43 | def toXML: xml.Node = {
44 |
45 | { root.toXML }
46 | { for ((k, v) <- vars) yield }
47 |
48 | }
49 |
50 | def advance(dt: Double): Unit = {
51 | root.advance(dt)
52 | }
53 | }
54 |
55 | object Drawing {
56 | def apply(): Drawing = {
57 | new Drawing(mutable.Map())
58 | }
59 |
60 | def apply(n: xml.Node): Drawing = {
61 | val vars = mutable.Map((n \ "var").map(vnode => (vnode \ "@key").text -> (vnode \ "@value").text.toDouble): _*)
62 | val drawing = new Drawing(vars)
63 | drawing.root = DrawTransform(n \ "drawable", drawing)
64 | drawing
65 | }
66 |
67 | def colorToXML(color: Color): xml.Node = {
68 |
69 | }
70 |
71 | def xmlToColor(n: xml.NodeSeq): Color = {
72 | Color((n \ "@red").text.toDouble, (n \ "@green").text.toDouble, (n \ "@blue").text.toDouble, (n \ "@opacity").text.toDouble)
73 | }
74 | }
--------------------------------------------------------------------------------