├── README.md ├── interviewMaterials └── interview_basic_questions.docx ├── partners ├── Axway.png ├── Paysafe.jpg ├── ProxiadBulgaria.png ├── SAP_Labs_Bulgaria.png └── SITEGROUND.png ├── week01 ├── 1.Monday │ ├── README.md │ ├── agenda.md │ └── prereading.md ├── 2.Wednesday │ ├── README.md │ └── prereading.md ├── 3.Friday │ ├── README.md │ ├── nokia.jpg │ └── prereading.md └── README.md ├── week02 ├── 1.Monday │ ├── Polyglot │ │ ├── README.md │ │ ├── polyglot.db │ │ └── polyglot.py │ ├── README.md │ ├── agenda.md │ └── prereading.md ├── 2.Wednesday │ ├── README.md │ ├── agenda.md │ └── prereading.md ├── 3.Friday │ ├── README.md │ ├── agenda.md │ └── prereading.md └── README.md ├── week03 ├── 1.Monday │ ├── README.md │ └── prereading.md ├── 2.Wednesday │ ├── README.md │ ├── decipher │ │ ├── HistogramCreator.java │ │ ├── Main.java │ │ └── MapUtil.java │ └── prereadings.md ├── 3.Friday │ ├── README.md │ ├── hashMap │ │ ├── Entry.java │ │ ├── MyHashMap.java │ │ └── Test.java │ └── prereadings.md └── README.md ├── week04 └── 3.Friday │ ├── README.md │ └── prereading.md ├── week05 ├── 1.Monday │ └── README.md └── 2.Wednesday │ └── VatTaxCalculator │ └── src │ ├── Country.java │ ├── CountryManager.java │ ├── Main.java │ ├── NotSupportedCountryException.java │ └── VatTaxCalculator.java ├── week06 ├── 1.Wednesday │ ├── README.md │ └── prereadings.md └── 2.Friday │ ├── README.md │ └── prereadings.md ├── week07 ├── 1.Monday │ ├── Examples │ │ └── src │ │ │ ├── FileUtils.java │ │ │ ├── Main.java │ │ │ └── User.java │ ├── README.md │ ├── prereading.md │ └── testData.zip └── 2.Wednesday │ ├── README.md │ ├── UnitTestsIntro │ └── src │ │ ├── categories │ │ ├── CategoriesTest.java │ │ ├── FastTests.java │ │ └── SlowTests.java │ │ ├── fibonacci │ │ ├── Fibonacci.java │ │ └── FibonacciTest.java │ │ ├── simple │ │ ├── DemoTest.java │ │ ├── SimpleCalculator.java │ │ └── SimpleCalculatorTest.java │ │ └── suits │ │ ├── A.java │ │ ├── ABTest.java │ │ ├── ATest.java │ │ ├── B.java │ │ └── BTest.java │ └── prereading.md ├── week08 ├── 1.Monday │ ├── 1-Peer-Review │ │ ├── GroupMatcher │ │ │ ├── .idea │ │ │ │ ├── .name │ │ │ │ ├── compiler.xml │ │ │ │ ├── copyright │ │ │ │ │ └── profiles_settings.xml │ │ │ │ ├── encodings.xml │ │ │ │ ├── misc.xml │ │ │ │ ├── modules.xml │ │ │ │ └── workspace.xml │ │ │ ├── GroupMatcher.iml │ │ │ ├── out │ │ │ │ └── production │ │ │ │ │ └── GroupMatcher │ │ │ │ │ ├── Main.class │ │ │ │ │ └── org │ │ │ │ │ └── hackbulgaria │ │ │ │ │ ├── Matcher.class │ │ │ │ │ ├── Pair.class │ │ │ │ │ └── Person.class │ │ │ ├── people.txt │ │ │ └── src │ │ │ │ ├── Main.java │ │ │ │ └── org │ │ │ │ └── hackbulgaria │ │ │ │ ├── Matcher.java │ │ │ │ ├── Pair.java │ │ │ │ └── Person.java │ │ ├── README.md │ │ └── rotations.md │ └── prereading.md └── 2.Friday │ ├── README.md │ └── prereading.md ├── week09 ├── 1.Monday │ ├── README.md │ └── prereading.md ├── 2.Wednesday │ ├── README.md │ └── prereading.md └── 3.Friday │ ├── README.md │ └── prereading.md ├── week10 ├── 1.Monday │ ├── README.md │ ├── prereading.md │ └── producer_consumer │ │ └── ProducerConsumer.java ├── 2.Wednesday │ ├── README.md │ └── prereading.md └── 3.Friday │ ├── README.md │ ├── prereading.md │ └── producer_consumer │ └── ProducerConsumer.java ├── week11 ├── 1.Monday │ ├── README.md │ └── prereading.md ├── 2.Wednesday │ ├── README.md │ └── prereading.md └── 3.Friday │ ├── Axway_JAAS_HackBulgaria_2016.pptx │ ├── HackBulgariaJAASReferenceProject │ ├── .project │ ├── .settings │ │ └── org.eclipse.jdt.core.prefs │ ├── bin │ │ └── com │ │ │ └── axway │ │ │ └── cdg │ │ │ └── jaas │ │ │ └── reference │ │ │ └── project │ │ │ ├── framework │ │ │ ├── RefJAASCallbackHandler.class │ │ │ └── UserPrincipal.class │ │ │ ├── main │ │ │ └── MyFirstJAASApplication.class │ │ │ └── modules │ │ │ ├── StandardLoginModule.class │ │ │ └── UsernameLoginModule.class │ ├── jaas.config │ ├── src │ │ └── com │ │ │ └── axway │ │ │ └── cdg │ │ │ └── jaas │ │ │ └── reference │ │ │ └── project │ │ │ ├── framework │ │ │ ├── RefJAASCallbackHandler.java │ │ │ └── UserPrincipal.java │ │ │ ├── main │ │ │ └── MyFirstJAASApplication.java │ │ │ └── modules │ │ │ ├── StandardLoginModule.java │ │ │ └── UsernameLoginModule.java │ └── users.properties │ └── README.md ├── week12 ├── 1.Monday │ ├── README.md │ ├── jdom-1.1.3.zip │ ├── prereading.md │ └── rome-1.0.jar ├── 2.Wednesday │ ├── README.md │ └── prereading.md └── 3.Friday │ ├── README.md │ └── prereading.md ├── week13 └── 1.Monday │ ├── README.md │ ├── input.txt │ └── teams.md ├── week14 ├── 1.Monday │ ├── README.md │ └── prereading.md └── 3.Friday │ ├── Java8Problems │ ├── .project │ ├── .settings │ │ ├── org.eclipse.jdt.core.prefs │ │ └── org.eclipse.m2e.core.prefs │ ├── pom.xml │ ├── src │ │ └── com │ │ │ └── hackbulgaria │ │ │ └── corejava101 │ │ │ ├── StudentOperations.java │ │ │ └── data │ │ │ ├── Gender.java │ │ │ ├── Student.java │ │ │ └── StudentsDataFactory.java │ └── test │ │ └── com │ │ └── hackbulgaria │ │ └── corejava101 │ │ └── StudentOperationsImplTest.java │ ├── README.md │ └── prereading.md ├── week15 └── 1.Monday │ └── README.md ├── week16 ├── Nat │ ├── README.md │ └── src │ │ └── com │ │ └── hackbulgaria │ │ └── java101 │ │ └── nat │ │ ├── Nat.java │ │ ├── NatTest.java │ │ ├── Succ.java │ │ └── Zero.java ├── Polynomials │ └── README.md └── threading │ ├── pom.xml │ └── src │ └── main │ └── java │ └── io │ └── github │ └── ivanvergiliev │ ├── FalseSharing.java │ ├── FirstCompletedFutures.java │ ├── FirstCompletedThreads.java │ ├── ForEachProgression.java │ ├── LockUsage.java │ ├── NonVolatileFlag.java │ ├── ParallelSumFutures.java │ ├── ParallelSumStream.java │ ├── ParallelSumThreads.java │ ├── ParallelSumThreadsLambda.java │ ├── SortByLength.java │ ├── SortByLengthLambda.java │ ├── StreamJava7.java │ ├── StreamJava8.java │ ├── SumPlusEquals.java │ ├── SumPlusPlus.java │ ├── ThreadSafeAdder.java │ ├── ThreadSafeFibonacciAdder.java │ ├── Unjoined.java │ ├── Unjoined1.java │ ├── Unordered.java │ ├── UnorderedInterleaved.java │ ├── UnorderedJoinAll.java │ └── UnorderedJoinImmediately.java ├── week17 ├── 1.Tuesday │ ├── bonus_task.md │ ├── complexities.md │ ├── prereadings │ │ ├── complexity_analysis.md │ │ ├── searching.md │ │ └── sorting.md │ └── tasks.md └── 2.Thursday │ ├── Build-Scripts.md │ ├── Closest-Coffee-Store.md │ ├── Phone-Numbers.md │ ├── Valid-Directories.md │ └── prereadings │ ├── graph.md │ ├── graph_properties.md │ ├── graph_representations.md │ └── graph_traversals.md └── week18 ├── 1.Tuesday └── prereadings.md └── 3.Saturday ├── speaker-notes.md └── workshop-notes.md /README.md: -------------------------------------------------------------------------------- 1 | # Programming101-Java 2 | 3 | Course materials & problems for HackBulgaria's Programming 101 with Java. Starting November 2015. 4 | 5 | ## Partners 6 | 7 | The course is happening thanks to: 8 | 9 | [![Paysafe](partners/Paysafe.jpg)](https://www.paysafe.com/) 10 | [![Proxiad Bulgaria](partners/ProxiadBulgaria.png)](http://www.proxiad.com/english/) 11 | [![Axway](partners/Axway.png)](https://www.axway.com/en) 12 | [![SAP Labs Bulgaria](partners/SAP_Labs_Bulgaria.png)](https://go.sap.com/bulgaria/index.html) 13 | 14 | ## Hosting Partners 15 | 16 | [![SiteGround](partners/SITEGROUND.png)](https://www.siteground.com/) 17 | 18 | ## Course Program 19 | 20 | This is a detailed program about the course, separated in weeks 21 | 22 | ### [Week 1](https://github.com/HackBulgaria/Programming101-Java/blob/master/week01) 23 | 24 | * Installing Linux 25 | * Introducing Java with syntax, types & language constructs 26 | * Problem solving & debugging using Java 27 | 28 | ### [Week 2](https://github.com/HackBulgaria/Programming101-Java/blob/master/week01) 29 | 30 | * Introducing shell & basic Linux commands 31 | * Working with Java command-line tools - java, javac, jar 32 | * Introducing git and GitHub 33 | 34 | ### Week 3 35 | 36 | * Introducing Java OOP concepts & solving OOP problems. 37 | * Classes, methods, attributes, constructors, scope modifiers, static stuff, etc. 38 | 39 | ### Week 4 40 | 41 | * Introducing Generic Types 42 | * Introducing Java Collections & data structures in Java 43 | * Solving problems with different data structures. 44 | 45 | 46 | ### Week 5 47 | 48 | * Second take on Java OOP concepts 49 | * Interfaces 50 | * Inheritence & Abstract Classes 51 | * Polymorhism 52 | 53 | ### Week 6 54 | 55 | * Third take on Java OOP concepts 56 | * Implementing multiple interfaces 57 | * Nested & Anonymous classes. 58 | * Java OOP quirks 59 | 60 | ### Week 7 61 | 62 | * Introducing IO in Java - Files & Streams 63 | * Dealing with exceptions in Java 64 | 65 | ### Week 8 66 | 67 | * Introducing Test Driven Development with jUnit 68 | * Introducing review process in software development 69 | * Working with tools like checkstyle and PMD 70 | 71 | ### Week 9 72 | 73 | * Introducing Threads in Java 74 | * Working with Java concurrency. 75 | * Blowing our minds. 76 | 77 | ### Week 10 78 | 79 | * Looking at the bigger picture - objected oriented design 80 | * Desining larger systems & making bigger software projects using everything we know up to now. 81 | 82 | ### Week 11 83 | 84 | * Introducing databases - SQL, JDBC 85 | 86 | ### Week 12 87 | 88 | * Introducing Maven 89 | * Working with 3rd party libraries, like Apache HTTP Client 90 | 91 | ### Week 13 92 | 93 | * Working with annotations & reflections 94 | * Introducing the concept for ORM with Hibernate 95 | 96 | ### Week 14 97 | 98 | * Java 8 & Functional programming in Java 99 | * Working with Servlets & Tomcat 100 | * How to distribute software? Deployment process with Maven / Ant / Gradle. 101 | 102 | ### Week 15 - Week 16 103 | 104 | * Introducing and working with Spring 105 | -------------------------------------------------------------------------------- /interviewMaterials/interview_basic_questions.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/interviewMaterials/interview_basic_questions.docx -------------------------------------------------------------------------------- /partners/Axway.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/partners/Axway.png -------------------------------------------------------------------------------- /partners/Paysafe.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/partners/Paysafe.jpg -------------------------------------------------------------------------------- /partners/ProxiadBulgaria.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/partners/ProxiadBulgaria.png -------------------------------------------------------------------------------- /partners/SAP_Labs_Bulgaria.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/partners/SAP_Labs_Bulgaria.png -------------------------------------------------------------------------------- /partners/SITEGROUND.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/partners/SITEGROUND.png -------------------------------------------------------------------------------- /week01/1.Monday/README.md: -------------------------------------------------------------------------------- 1 | ### Verify java is working and is in $PATH ### 2 | ```java -version``` 3 | 4 | ```javac -version``` 5 | 6 | ```javap -version``` 7 | 8 | Friendly advice: These should be the same version, or you might have a bad time :) 9 | 10 | ### Compiling fun with javac and java### 11 | - Open a terminal. Navigate to any folder whatsoever. Make a new Empty.java file. Try to compile it with javac. See what happens. 12 | - Make a class named Program. Try to compile it with javac. 13 | - Rename the class to Empty. Compile it. 14 | - Make a main method. Make it print "Hello world!". Compile it and run it. 15 | - Make the main method print its arguments (String[] args). Make the for loop as you would make one in C or C++, and use the System.out.println method for printing to the console. 16 | 17 | ### Getting to know what classpath is### 18 | - Open a terminal, navigate to some folder. Make a new A.java file with a legitimate class A declared in it. 19 | - Do the same for a file/class named B. 20 | - Declare a public method in B. 21 | - In class A, make a *main method* 22 | - Instantiate B in it and call B's public method. 23 | - Try, compile and run A. Does it run? Why? How does it know about B? What about import statements? 24 | 25 | - Now move B up one folder to '..' 26 | - Try compiling and running it. 27 | 28 | - Add -cp ".." to your javac command and try again. 29 | 30 | ###Bundle them both### 31 | - jar -c A.class 32 | - Does this command look familiar to you? : ) 33 | 34 | ### Disassembly with javap ### 35 | - Disassemble Empty.class 36 | - Does this look familiar to you? This is what Eclipse is doing when you open a look up a class file with no source attached. 37 | 38 | -------------------------------------------------------------------------------- /week01/1.Monday/agenda.md: -------------------------------------------------------------------------------- 1 | ### Agenda #1 ### 2 | - Представете се 3 | - Малко организационно: 4 | - как ще протече курса: 5 | - прочели сте вкъщи материала, който ще използваме днес, 6 | - тук разказваме и обобщаваме материала, 7 | - решаваме задачи и четем още материали тук 8 | - и накрая решавате още повече и четете материали за следващия път вкъщи. 9 | - Java - a little history 10 | + started as 'Oak' in 1991 => дъб 11 | + Created by Sun 12 | + renamed to 'java', due to large ammounts of coffee the team used in development 13 | + released 1995 14 | + James Gosling 15 | + Brian Goetz(threading), Tim Peierls(threading), Joshua Bloch(annotations, collections, try-with-resource), Doug Lea (threading), Mark Reinhold(module system), Alex Buckley(generics), Neal Gafter(javac) (http://enos.itcollege.ee/~jpoial/allalaadimised/jdk7/jls7.pdf) 16 | + Java 17 | + Compile once, run everywhere 18 | #1 Development Platform 19 | 9 Millions Developers 20 | 1 Billion Java Downloads per Year 21 | 3 Billion devices run Java 22 | 97% of Enterprise Desktops run Java 23 | 100% of BLU-RAY Disc Players ship with Java 24 | http://www.javacodegeeks.com/2014/03/java-facts-to-blow-your-mind.html 25 | Jit Compiler in J2SE (Java 1.2) 26 | - Java, JRE, JVM, JDK 27 | - JSR, JCP 28 | - JSE, J2EE, J2ME 29 | - Sun, Oracle, Google 30 | - Cross-platform, compatibility 31 | - Javac 32 | - classpath 33 | 34 | //what IDE does for us 35 | C:\>javac -sourcepath src -classpath classes;lib\Banners.jar ^ 36 | src\farewells\GoodBye.java -d classes 37 | //source and target explanations 38 | C\:>javac -sodurce 1.6 -target 1.6 -bootclasspath C:\jdk1.6.0\lib\rt.jar ^ 39 | -extdirs "" OldCode.java 40 | 41 | //bootclasspath option 42 | 43 | - javap 44 | - the javadoc tool 45 | - jar format 46 | - Common VM Arguments 47 | 48 | - if possible - Welcome to Eclipse 49 | -Coding style format import 50 | -Import Preferences and Quick Keys setup (Refactor Menu, Create getter, setter) 51 | -Hello world from Eclipse 52 | -Packages,Eclipse Views 53 | -------------------------------------------------------------------------------- /week01/1.Monday/prereading.md: -------------------------------------------------------------------------------- 1 | ##Start Here!## 2 | 3 | Welcome :) 4 | 5 | Here are a few things you should probably get done before the start of the Programming 101 - java course: 6 | 7 | **1)** Install JDK 8 ( Java SE Development Kit ) from [oracle website](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)- we will work with it. You can follow [this guide](http://askubuntu.com/a/55960). 8 | 9 | **2)** Make sure java binaries are registered in PATH 10 | and that they are **the same version** 11 | 12 | ``` 13 | java -version 14 | 15 | java version "1.8.0_65" 16 | Java(TM) SE Runtime Environment (build 1.8.0_65-b17) 17 | Java HotSpot(TM) 64-Bit Server VM (build 25.65-b01, mixed mode) 18 | ``` 19 | ``` 20 | javac -version 21 | javac 1.8.0_65 22 | ``` 23 | 24 | **3)** Install Eclipse Mars from [Eclipse site] 25 | (https://eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/mars/1/eclipse-java-mars-1-linux-gtk-x86_64.tar.gz&mirror_id=1190) 26 | 27 | or use the [installer](https://www.eclipse.org/downloads/) 28 | 29 | **4)** Read the [Google style-guide](http://google-styleguide.googlecode.com/svn/trunk/javaguide.html) for Java source code: 30 | 31 | We will be using very similiar style guide, but with the following modifications: 32 | - 4 spaces for identation instead of 2. 33 | - 120 lines for line-wrapping instead of 80. 34 | 35 | **5)** Create yourself a GitHub account! 36 | If you have never worked with git or GitHub, see the [excellent article](https://github.com/HackBulgaria/Programming101/tree/master/week1/git.md) from 37 | HackBulgaria's programming 101 course: 38 | 39 | ## Installing Linux 40 | 41 | We suggest using the Ubuntu Long Term Support (LTS) version: [14.04.03] 42 | (http://www.ubuntu.com/download/desktop) 43 | 44 | Before moving on and installing any Linux, **PLEASE BACKUP EVERYTHING THAT IS IMPORTANT TO YOU**. 45 | 46 | Don't leave memories only on the hard drive of your PC / laptop. It will eventually fail and you will eventually lose everything that is not backed up. 47 | 48 | Our suggestion is, use one or more of the following: 49 | 50 | * [pcloud](https://www.pcloud.com/) 51 | * [DropBox](https://www.dropbox.com/) 52 | * Other similar cloud services 53 | -------------------------------------------------------------------------------- /week01/2.Wednesday/prereading.md: -------------------------------------------------------------------------------- 1 | ###If you have problems installing Ubuntu### 2 | 3 | You can install (hope so) it on a virtual machine: 4 | http://www.wikihow.com/Install-Ubuntu-on-VirtualBox 5 | 6 | JRE, JDK, JVM (if you still don't know what they are) 7 | http://stackoverflow.com/questions/11547458/what-is-differences-between-jvm-jdk-jre-openjdk 8 | 9 | Path and classpath (if you are having trouble differentiating those two) 10 | http://docs.oracle.com/javase/tutorial/essential/environment/paths.html 11 | 12 | On debugging with Eclipse 13 | https://blog.codecentric.de/en/2013/04/again-10-tips-on-java-debugging-with-eclipse/ 14 | 15 | Primitive Data types in Java 16 | http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html 17 | 18 | Arrays in Java 19 | http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html 20 | http://stackoverflow.com/questions/2267790/how-are-arrays-implemented-in-java 21 | http://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html#jls-10.8 22 | 23 | Some Q&A 24 | http://docs.oracle.com/javase/tutorial/java/nutsandbolts/QandE/questions_variables.html 25 | 26 | Operators 27 | http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html 28 | http://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html 29 | 30 | On Control flow - if, for, while, do-while, switch 31 | http://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html 32 | 33 | -------------------------------------------------------------------------------- /week01/3.Friday/nokia.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/week01/3.Friday/nokia.jpg -------------------------------------------------------------------------------- /week01/3.Friday/prereading.md: -------------------------------------------------------------------------------- 1 | ###If you have problems installing Ubuntu### 2 | 3 | You can install (hope so) it on a virtual machine: 4 | http://www.wikihow.com/Install-Ubuntu-on-VirtualBox 5 | 6 | Wrapper Classes 7 | http://en.wikipedia.org/wiki/Primitive_wrapper_class 8 | 9 | On autoboxing and unboxing in Java 10 | http://javarevisited.blogspot.com/2012/07/auto-boxing-and-unboxing-in-java-be.html 11 | 12 | On instanceof and isAssignableFrom 13 | http://stackoverflow.com/questions/496928/what-is-the-difference-between-instanceof-and-class-isassignablefrom 14 | 15 | Most important stuff on String 16 | http://javarevisited.blogspot.com/2013/07/java-string-tutorial-and-examples-beginners-programming.html 17 | 18 | StringBuilder vs StringBuffer? 19 | http://javarevisited.blogspot.com/2011/07/string-vs-stringbuffer-vs-stringbuilder.html 20 | 21 | On Unicode (Joel on Software) 22 | http://www.joelonsoftware.com/articles/Unicode.html 23 | 24 | On String interning 25 | http://en.wikipedia.org/wiki/String_interning 26 | http://java-performance.info/string-intern-in-java-6-7-8/ -------------------------------------------------------------------------------- /week01/README.md: -------------------------------------------------------------------------------- 1 | [Monday](https://github.com/HackBulgaria/Programming101-Java/blob/master/week01/1.Monday) 2 | [Wednesday](https://github.com/HackBulgaria/Programming101-Java/blob/master/week01/2.Wednesday) 3 | [Friday](https://github.com/HackBulgaria/Programming101-Java/blob/master/week01/3.Friday) 4 | 5 | -------------------------------------------------------------------------------- /week02/1.Monday/Polyglot/README.md: -------------------------------------------------------------------------------- 1 | Polyglot 2 | ======== 3 | 4 | The problem where you meet new languages and compile them, to solve a puzzle! 5 | 6 | ## Setup 7 | 8 | You will need sqlite3 in order to run the Polyglot problem: 9 | 10 | ``` 11 | $ sudo apt-get install sqlite3 12 | ``` 13 | 14 | ## How to run the program? 15 | 16 | To start everything, type: 17 | 18 | ``` 19 | $ python3.4 polyglot.py 20 | 21 | Hello and Welcome! 22 | I am the compiler. 23 | You can ask me to output different source files. 24 | I will provide guides for compiling too.When you are ready, you can provide me with the answer from the code. 25 | And I will reveal a secret to you! 26 | Type help, to get you started. 27 | Enter command> 28 | 29 | ``` 30 | 31 | Now you can enter different commands in order to start the task: 32 | 33 | * `help` command will list you everything 34 | * `list` command will give you all languages and their status 35 | * `start ` will create a new folder with the given language. It is time to solve the language puzzle! (Ctrl-C to exit `polyglot.py`) 36 | * `answer ` - When you are ready with the given language, you can check if you answer is right. 37 | 38 | Good luck! 39 | 40 | Use Google & `apt-get` -------------------------------------------------------------------------------- /week02/1.Monday/Polyglot/polyglot.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/week02/1.Monday/Polyglot/polyglot.db -------------------------------------------------------------------------------- /week02/1.Monday/agenda.md: -------------------------------------------------------------------------------- 1 | - Linux -------------------------------------------------------------------------------- /week02/1.Monday/prereading.md: -------------------------------------------------------------------------------- 1 | More about `javac` 2 | http://www.codejava.net/java-core/tools/using-javac-command 3 | 4 | More about `jar` 5 | http://www.mkyong.com/java/the-java-archive-tool-jar-examples/ 6 | 7 | More about `java` 8 | http://www.sergiy.ca/how-to-compile-and-launch-java-code-from-command-line/ 9 | 10 | What is `classpath`? 11 | http://kevinboone.net/classpath.html 12 | 13 | **Now for some Linux magic** 14 | 15 | This is you when you learn how powerful Linux actually is: 16 | 17 | ![This is you](http://i44.tinypic.com/6h18c0.gif) 18 | 19 | Go through these tutorials: 20 | https://www.digitalocean.com/community/tutorial_series/getting-started-with-linux 21 | 22 | Some more magic: 23 | http://linuxcommand.org/lc3_learning_the_shell.php 24 | 25 | A really useful Linux commands cheatsheet: 26 | http://cli.learncodethehardway.org/bash_cheat_sheet.pdf -------------------------------------------------------------------------------- /week02/2.Wednesday/README.md: -------------------------------------------------------------------------------- 1 | ## Object-Oriented Programming 2 | ### 23. Fast and Furious 3 | Make a class Car. 4 | Make subtypes of Car, representing the following brands of cars: Audi, BMW, Volkswagen, Honda and Skoda. 5 | 6 | Each subtype should have a method `boolean isEcoFriendly(boolean testing)`, which does the following: 7 | - For a Volkswagen car, if `testing` is `true`, it should return `true`. Return `false` otherwise. 8 | - For any other car, return `true`. 9 | 10 | Later, for the Audi type you need to return its mileage, because all the German brand manufacturers require it - how you will do it? 11 | 12 | ### 24. The Time Lord 13 | 14 | Make a class `Time` to hold information about the current time and *the current date* . 15 | 16 | Make an *easy-to-use* constructor (from client perspective), that would represent the time and date the client wants to hold in your class. 17 | 18 | Implement the toString() method, returning the time and date in format : "hh:mm:ss dd.MM.YY". 19 | 20 | Check out String.format method 21 | 22 | *Bonus* 23 | Make a factory method `now()` for your class, returning the Time at the present moment :) 24 | 25 | See http://en.wikipedia.org/wiki/Factory_method_pattern 26 | 27 | ### 25. Pair 'em up 28 | 29 | Make a class `Pair`, representing a pair of *Objects* (later we will revisit this with Generics) 30 | 31 | Create getter methods for the first and second member of the pair. 32 | http://stackoverflow.com/questions/2036970/how-do-getters-and-setters-work 33 | 34 | Implement the toString method, giving a meaningful representation of the class. 35 | Override the equals method from Object => two pairs are equal if both their members are equal. 36 | 37 | Make the class *immutable*. 38 | ### 26. Stack 'em 39 | 40 | Create and implement a class `StackImpl`, representing a... well, stack. 41 | 42 | Think about all the required (public) operations needed, so that one can use a stack class. You know, stuff like actually pushing an element, popping an element, length, clear, isEmpty, stuff like that. Think about the return types of those operations (see task 5, you may get a hint about one). *Extract them all to an interface `Stack`, which your class should implement*. 43 | 44 | ### 27. No clones allowed. 45 | 46 | Create an implementation of your `Stack` interface, which has the added invariant: 47 | -It does not allow an element to be duplicated. If there is an element 'a' in the stack, and some smart guy pushes 'a' again, his operation should fail, and the smart guy should have a way to know this. 48 | 49 | 50 | ### 28. On two fronts 51 | 52 | Implement a (doubly-linked) list (using ints only). Just as before, extract all of its required public operations in an interface. Some of those operations are add, *remove*, size, get(int elementIndex), getHead (getFirst), getTail(getLast), etc. 53 | Think good and hard about your implementation, and whether you will need another class for a List Node. 54 | 55 | ### 29. Mr. ListStack 56 | Implement your own `Stack` with your own (doubly) `LinkedList` class : ) 57 | 58 | *Bonus* implement a unique stack just as before, but using your `LinkedList` and an *anonymous implementation*, combined with a factory method. 59 | See http://www.programmerinterview.com/index.php/java-questions/java-anonymous-class-example/ 60 | 61 | Return your anonymous implementation from a factory method! 62 | 63 | ### 30. The One 64 | Make a mutable class 'Matrix' represeting a NxM (Pixel[][]) matrix. `Pixel` is a POJO (Google it!) containing three float values - R, G, B. Think good about your constructors, your data. Your goal is to make this class as convenient as possible for the person using it. 65 | 66 | Your class `Matrix` should have another cool thing about it => it would allow operations with every pixel. 67 | In order for this to work, your class should declare a public method `operate(MatrixOperation op)` 68 | 69 | Where `MatrixOperation` is an interface, containing a method 'Pixel withPixel(int x, int y, Pixel[][] matrix)'. 70 | *Think - why are we getting x, y, and the matrix instead of just passing the pixel value?* 71 | 72 | Implement the toString(), converting the whole matrix into a String in a way that it would be visible on the console. 73 | 74 | The method should `operate(MatrixOperation op)` should call the `withPixel` method for every x and y in the matrix and assign the result of `withPixel` to the matrix. 75 | 76 | Now that you have this, implement: 77 | - brightness reduce 78 | - grayscale 79 | - gaussian blur (optional) -------------------------------------------------------------------------------- /week02/2.Wednesday/agenda.md: -------------------------------------------------------------------------------- 1 | - Everything is OOP! Java or not? 2 | - What is a class? What is an object? What is instance? What is type? 3 | - Method overloading, method overriding 4 | - State/behaviour 5 | - Data Encapsulation, Subtype polymorphism, Liskov Principle 6 | - Object, equals, hashCode, getClass, toString, wait, notify, notifyAll 7 | - Constructors, on object construction in java, what happens on new()... 8 | - public, private, protected, default 9 | - static -------------------------------------------------------------------------------- /week02/2.Wednesday/prereading.md: -------------------------------------------------------------------------------- 1 | On OOP in General 2 | https://www.youtube.com/watch?v=lbXsrHGhBAU 3 | 4 | OOP Trail @ Oracle 5 | http://docs.oracle.com/javase/tutorial/java/concepts/index.html 6 | 7 | Class and Objects @ Oracle (Those pages are actually Sun's property!) 8 | http://docs.oracle.com/javase/tutorial/java/javaOO/ 9 | http://docs.oracle.com/javase/tutorial/java/concepts/object.html 10 | 11 | More on Classes and objects 12 | http://www.javaworld.com/article/2075202/core-java/object-oriented-language-basics-part-1.html?page=1 13 | 14 | Constructors & new() 15 | http://www.javaworld.com/article/2076204/core-java/understanding-constructors.html 16 | http://www.javaworld.com/article/2076614/core-java/object-initialization-in-java.html 17 | 18 | Abstract classes vs Interfaces 19 | http://www.programmerinterview.com/index.php/java-questions/interface-vs-abstract-class/ 20 | http://www.javaworld.com/article/2077421/learn-java/abstract-classes-vs-interfaces.html?null 21 | 22 | Override, overload, hide 23 | http://docs.oracle.com/javase/tutorial/java/IandI/override.html 24 | 25 | Subtyping & Liskov principle 26 | https://www.youtube.com/watch?v=IL61KMYK0b8 27 | 28 | Default Methods 29 | http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html 30 | 31 | Invariants 32 | http://people.cs.aau.dk/~normark/oop-csharp/html/notes/contracts_themes-class-inv-sect.html -------------------------------------------------------------------------------- /week02/3.Friday/agenda.md: -------------------------------------------------------------------------------- 1 | - GIT + Github 2 | -------------------------------------------------------------------------------- /week02/README.md: -------------------------------------------------------------------------------- 1 | [Monday](https://github.com/HackBulgaria/Programming101-Java/blob/master/week02/1.Monday) 2 | [Wednesday](https://github.com/HackBulgaria/Programming101-Java/blob/master/week02/2.Wednesday) 3 | [Friday](https://github.com/HackBulgaria/Programming101-Java/blob/master/week02/3.Friday) 4 | -------------------------------------------------------------------------------- /week03/1.Monday/README.md: -------------------------------------------------------------------------------- 1 | # Generic Problems 2 | 3 | ## 1.Generic backpack 4 | 5 | You need a digital backback. Make a simple class that takes a single object of any type. The class should use generics. Make getters and setters for the field. 6 | 7 | ## 2.Pair 8 | 9 | In Java you are limited to return only one object from a method. In same cases this could be an inconvenience. One workaround is to make a class that holds two objects, so you can have multiple returned objects. 10 | 11 | Make the class pair from the last week generic. It should hold two objects from arbitrary type. Make getters and setters. 12 | 13 | ## 3.Triple 14 | 15 | Well, you may also need to return 3 objects from a function. Make a class named Triple that holds ... well three object of arbitrary type. Make getters and setters. 16 | 17 | ## 4.Sumation function 18 | 19 | Make function that sums two numbers. It should be able to sum every type of number Byte, Int, Long, Float, Double, BigInt. 20 | 21 | Hint: there may be something in common in all this classes, actually you should already know if you have read the prereadings. :) 22 | 23 | ## 5.Subtraction function 24 | 25 | Make function that subtracts two numbers. It should be able to subtract every type of number Byte, Int, Long, Float, Double, BigInt. 26 | 27 | ## 6.Multiplication function 28 | 29 | The same as the previous, but it should multiplicate two numbers. 30 | 31 | ## 7.Division function 32 | 33 | It should multiply two numbers. 34 | 35 | ## 8.Power function 36 | 37 | It should rise a number to a given power. Let the exponent (the power number) be a whole positive number. 38 | 39 | Bonus: you can try to make it with negative and floating exponent. 40 | 41 | ## 9.Factorial function 42 | 43 | Once again the lovely factorial, this time make it work for any type of number. 44 | 45 | ## 10.Make it more generic 46 | 47 | * Remember the stack from the last week? Make it generic. 48 | * Remember the palindrom functions from the first week? Make a generic one. Think if you can define a universal palindrome function. 49 | * A long long time ago in a galaxy far away (Mladost 3, Resen str, 16.11.2015) you have implemented a function that finds the minimum element of an array. Guess what... you should make it generic. Let the force be with you. 50 | 51 | The force: Think on which classes we can find the minimum. 52 | 53 | ## 11. Yet another vector. 54 | 55 | Implement the vector Abstract Data type. It should be resize-able and have all neccessary methods. Hey It should be generic. 56 | -------------------------------------------------------------------------------- /week03/1.Monday/prereading.md: -------------------------------------------------------------------------------- 1 | [Generics](https://docs.oracle.com/javase/tutorial/java/generics/) starter pack. Go through the all lesson or at least up to Type Erasure. -------------------------------------------------------------------------------- /week03/2.Wednesday/decipher/HistogramCreator.java: -------------------------------------------------------------------------------- 1 | package decipher; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public class HistogramCreator { 7 | 8 | public static Map getHistogram(String cryptedString) { 9 | String processedInput = cryptedString.replaceAll("\\W", ""); 10 | 11 | Map histogram = new HashMap<>(); 12 | 13 | for(int i=0; i < processedInput.length(); i++) { 14 | Character ch = Character.toLowerCase(processedInput.charAt(i)); 15 | if(histogram.containsKey(ch)) { 16 | histogram.put(ch, histogram.get(ch)+1); 17 | } else { 18 | histogram.put(ch, 1); 19 | } 20 | } 21 | 22 | return histogram; 23 | } 24 | 25 | 26 | } 27 | -------------------------------------------------------------------------------- /week03/2.Wednesday/decipher/Main.java: -------------------------------------------------------------------------------- 1 | package decipher; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | public class Main { 7 | 8 | public static void main(String[] args) { 9 | Map map = HistogramCreator.getHistogram("bcdaab"); 10 | List charList = MapUtil.sortByValue(map); 11 | System.out.println(charList); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /week03/2.Wednesday/decipher/MapUtil.java: -------------------------------------------------------------------------------- 1 | package decipher; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.Comparator; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.Map.Entry; 9 | 10 | public class MapUtil { 11 | 12 | public static > List sortByValue(Map map) { 13 | List sortedList = new ArrayList<>(); 14 | 15 | List> entries = new ArrayList<>(map.entrySet()); 16 | // performs descending sort 17 | Collections.sort(entries, new Comparator>() { 18 | 19 | @Override 20 | public int compare(Entry firstEntry, Entry secondEntry) { 21 | return secondEntry.getValue().compareTo(firstEntry.getValue()); 22 | } 23 | 24 | }); 25 | 26 | for (Entry entry : entries) { 27 | sortedList.add(entry.getKey()); 28 | } 29 | 30 | return sortedList; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /week03/2.Wednesday/prereadings.md: -------------------------------------------------------------------------------- 1 | *Simplest use of an ArrayList* 2 | http://www.mkyong.com/java/how-to-loop-arraylist-in-java/ 3 | 4 | *Check out some of the public methods of ArrayList* 5 | See its behaviour, what it can and can't do :) 6 | http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html 7 | 8 | *Some examples of the most used collections class in Java: ArrayList* 9 | http://javarevisited.blogspot.com/2011/05/example-of-arraylist-in-java-tutorial.html 10 | 11 | *Difference between Iterator and ListIterator* (if you are unfamiliar with iterators, skip this one for now : ) 12 | http://stackoverflow.com/questions/10977992/difference-between-iterator-and-listiterator 13 | 14 | *Diagram of ALL of java's collections framework:* 15 | http://www.codejava.net/java-core/collections/overview-of-java-collections-framework-api-uml-diagram -------------------------------------------------------------------------------- /week03/3.Friday/README.md: -------------------------------------------------------------------------------- 1 | # More Problems with Collections 2 | 3 | ##1.Given a list of Students, sort them by grade 4 | 5 | Lets say you have a `List`, where a Student is a class, containing two fields: `name` and `grade`. 6 | 7 | Sort them by their grades first. Their grades actually are integers => 2,3,4,5,6. If two students happen to have the same grades, sort those two by their names. 8 | 9 | ##2.Implement a class ToDoList 10 | 11 | Imagine you have a world of stuff to do. 12 | Homeworks, courseworks, exams, even preparing for HackBulgaria! 13 | Unfortunately you do not have much time - you need to eat, you need to sleep, you need to have a good time. 14 | 15 | Now, you need to sort your priorities right! Make a class `ToDoList`, which supports the following operations: 16 | `void add(Task t)` 17 | `void markFinished(Task t)` 18 | `void markCancelled(Task t)` 19 | `Task getTop()` 20 | `boolean canFinish()` 21 | `int getRemainigTime()` //calculates the time remaining after you've done all of your tasks. 22 | 23 | ... where `Task` is a class which represents something you have to do. What data/methods should it have? What is common for all the tasks you need to get done? 24 | A `Task` should at the very least have a priority and a time required in order to finish. 25 | You should take an integer in your constructor - the ammount of hours available for each task. 26 | 27 | Example usage of your class: 28 | 29 | ```java 30 | ToDoList todo = new ToDoList(11); //11 hours remaining! 31 | todo.addTask(new StudyForAlgebraTask(10)); //maximum priority! 32 | todo.addTask(new LearnGeometryTask()); //default priority, smaller than 10 33 | todo.addTask(new GoOutTask(1.5f)); //default priority, smaller than 10 34 | todo.addTask(new SleepTask()); //straight 8 hours, of course! 35 | 36 | if (todo.canFinish()){ 37 | System.out.println("Woohoo!"); 38 | } else { 39 | System.out.println("I am ...screwed :("); 40 | } 41 | 42 | System.out.println(todo.top()) //StudyForAlgebraTask 43 | System.out.println(todo.getTimeNeeded()) //sum of the time needed for every task added in todo list 44 | ``` 45 | 46 | *Hints* 47 | See Comparable and Comparator classes in Java. Check out the PriorityQueue class. 48 | http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html 49 | 50 | ##3.Implement your own HashMap. 51 | 52 | It's up to choose how to resolve colisions. 53 | Use this link to see the most common approaches: 54 | https://en.wikipedia.org/wiki/Hash_table 55 | 56 | Make it iterative - one step at time. 57 | 58 | First make the basic functionality. 59 | You should be able to put, get and check if a given key is already in the map. 60 | 61 | Then make it resizable. 62 | You can choose 0.75 for load factor. 63 | 64 | When it is resizable and you can try to make it a bit generic. 65 | 66 | Finally your class can implement the Map interface. -------------------------------------------------------------------------------- /week03/3.Friday/hashMap/Entry.java: -------------------------------------------------------------------------------- 1 | package hashMap; 2 | 3 | public class Entry { 4 | private String _key; 5 | private Integer _value; 6 | 7 | public Entry(String key, Integer value) { 8 | setKey(key); 9 | setValue(value); 10 | } 11 | 12 | public String getKey() { 13 | return _key; 14 | } 15 | 16 | public void setKey(String _key) { 17 | this._key = _key; 18 | } 19 | 20 | public Integer getValue() { 21 | return _value; 22 | } 23 | 24 | public void setValue(Integer _value) { 25 | this._value = _value; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /week03/3.Friday/hashMap/MyHashMap.java: -------------------------------------------------------------------------------- 1 | package hashMap; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | 7 | public class MyHashMap { 8 | private int capacity; 9 | private List> buckets; 10 | 11 | public MyHashMap() { 12 | capacity = 16; // 16 is initial capcity 13 | buckets = new ArrayList<>(capacity); 14 | init(buckets, capacity); 15 | } 16 | 17 | private void init(List> buckets, int capacity) { 18 | for(int i=0; i()); 20 | } 21 | } 22 | 23 | private int hash(String key) { 24 | return Math.abs((key.hashCode() % capacity)); 25 | } 26 | 27 | public void put(String key, Integer value) { 28 | if (key == null) { 29 | return; 30 | } 31 | 32 | int position = hash(key); 33 | List bucket = buckets.get(position); 34 | 35 | if (bucket == null) { 36 | bucket = new LinkedList<>(); 37 | } 38 | 39 | for (Entry entry : bucket) { 40 | if (key.equals(entry.getKey())) { 41 | entry.setValue(value); 42 | return; 43 | } 44 | } 45 | 46 | Entry newEntry = new Entry(key, value); 47 | bucket.add(newEntry); 48 | } 49 | 50 | public Integer get(String key) { 51 | if (key == null) { 52 | return null; 53 | } 54 | 55 | int position = hash(key); 56 | List bucket = buckets.get(position); 57 | 58 | if (bucket == null) { 59 | return null; 60 | } 61 | 62 | for (Entry entry : bucket) { 63 | if (key.equals(entry.getKey())) { 64 | return entry.getValue(); 65 | } 66 | } 67 | 68 | return null; 69 | } 70 | 71 | public boolean containsKey(String key) { 72 | if (key == null) { 73 | return false; 74 | } 75 | 76 | Integer value = get(key); 77 | if (value != null) { 78 | return true; 79 | } 80 | return false; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /week03/3.Friday/hashMap/Test.java: -------------------------------------------------------------------------------- 1 | package hashMap; 2 | 3 | public class Test { 4 | 5 | public static void main(String[] args) { 6 | MyHashMap testMap = new MyHashMap(); 7 | testMap.put("test_1", 1); 8 | System.err.println(testMap.get("test_1")); 9 | testMap.put("test_1", 3); 10 | System.err.println(testMap.containsKey("test_1")); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /week03/3.Friday/prereadings.md: -------------------------------------------------------------------------------- 1 | *A HashMap example* 2 | http://www.tutorialspoint.com/java/java_hashmap_class.htm 3 | 4 | *HashMap vs Hashtable vs TreeMap in Java* 5 | http://www.programcreek.com/2013/03/hashmap-vs-treemap-vs-hashtable-vs-linkedhashmap/ 6 | 7 | *Equals and hashcode in java* 8 | http://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java 9 | 10 | *How HashMap works* 11 | http://www.javacodegeeks.com/2014/03/how-hashmap-works-in-java.html 12 | -------------------------------------------------------------------------------- /week03/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/week03/README.md -------------------------------------------------------------------------------- /week04/3.Friday/prereading.md: -------------------------------------------------------------------------------- 1 | # Four principles of Object-Oriented Programming 2 | 3 | #### 1) Encapsulation 4 | http://www.tutorialspoint.com/java/java_encapsulation.htm 5 | http://beginnersbook.com/2013/05/encapsulation-in-java/ 6 | 7 | #### 2) Inheritance 8 | http://www.tutorialspoint.com/java/java_inheritance.htm 9 | http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html 10 | 11 | #### 3) Abstraction 12 | http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html 13 | http://www.tutorialspoint.com/java/java_abstraction.htm 14 | http://www.javatpoint.com/abstract-class-in-java 15 | 16 | #### 4) Polymorphism 17 | https://en.wikipedia.org/wiki/Polymorphism_(computer_science) 18 | http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html 19 | http://www.tutorialspoint.com/java/java_polymorphism.htm 20 | 21 | # Interfaces 22 | http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html 23 | https://en.wikipedia.org/wiki/Interface_(Java) 24 | -------------------------------------------------------------------------------- /week05/2.Wednesday/VatTaxCalculator/src/Country.java: -------------------------------------------------------------------------------- 1 | 2 | public class Country { 3 | private final String mCountryId; 4 | private final String mName; 5 | private final boolean mIsDefault; 6 | private final double mVatTax; // from 0 to 1 7 | 8 | public Country(String countryId, String name, 9 | boolean isDefault, double vatTax) { 10 | 11 | if (vatTax < 0 || vatTax > 1) { 12 | throw new IllegalArgumentException("Invalid Vat Tax"); 13 | } 14 | 15 | mCountryId = countryId; 16 | mName = name; 17 | mIsDefault = isDefault; 18 | mVatTax = vatTax; 19 | } 20 | 21 | public String getCountryId() { 22 | return mCountryId; 23 | } 24 | 25 | public String getName() { 26 | return mName; 27 | } 28 | 29 | public boolean isDefault() { 30 | return mIsDefault; 31 | } 32 | 33 | public double getVatTax() { 34 | return mVatTax; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /week05/2.Wednesday/VatTaxCalculator/src/CountryManager.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Iterator; 3 | import java.util.Map; 4 | 5 | public class CountryManager { 6 | 7 | private static CountryManager sCountryManager; 8 | 9 | private HashMap mCountries = new HashMap<>(); 10 | private String mDefaultCountryKey; 11 | 12 | private CountryManager() { 13 | 14 | } 15 | 16 | private void initDefaultCountry() { 17 | Iterator> iterator = mCountries.entrySet().iterator(); 18 | while (iterator.hasNext()) { 19 | Map.Entry entry = iterator.next(); 20 | String key = entry.getKey(); 21 | Country country = entry.getValue(); 22 | if (country.isDefault()) { 23 | mDefaultCountryKey = key; 24 | } 25 | } 26 | } 27 | 28 | public static CountryManager getInstance() { 29 | if (sCountryManager == null) { 30 | sCountryManager = new CountryManager(); 31 | } 32 | 33 | return sCountryManager; 34 | } 35 | 36 | public Country getCountry(String countryCode) throws NotSupportedCountryException { 37 | 38 | if (!mCountries.containsKey(countryCode)) { 39 | throw new NotSupportedCountryException("Country not supported."); 40 | } 41 | 42 | return mCountries.get(countryCode); 43 | } 44 | 45 | public void changeDefaultCountry(Country newDefault) throws NotSupportedCountryException { 46 | String newDefaultId = newDefault.getCountryId(); 47 | 48 | Country country = getCountry(mDefaultCountryKey); 49 | mCountries.put(mDefaultCountryKey, 50 | new Country(mDefaultCountryKey, country.getName(), false, country.getVatTax())); 51 | mCountries.put(newDefaultId, 52 | new Country(newDefaultId, newDefault.getName(), true, newDefault.getVatTax())); 53 | 54 | mDefaultCountryKey = newDefaultId; 55 | } 56 | 57 | public void add(Country country) { 58 | mCountries.put(country.getCountryId(), country); 59 | initDefaultCountry(); 60 | } 61 | 62 | public void add(Country[] countries) { 63 | for (Country country : countries) { 64 | mCountries.put(country.getCountryId(), country); 65 | } 66 | initDefaultCountry(); 67 | } 68 | 69 | public void remove(Country country) { 70 | mCountries.remove(country.getCountryId()); 71 | } 72 | 73 | public void remove(Country[] countries) { 74 | for (Country country : countries) { 75 | mCountries.remove(country.getCountryId()); 76 | } 77 | } 78 | 79 | public String getDefaultCountryCode() { 80 | return mDefaultCountryKey; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /week05/2.Wednesday/VatTaxCalculator/src/Main.java: -------------------------------------------------------------------------------- 1 | 2 | public class Main { 3 | 4 | public static void main(String[] args) { 5 | 6 | CountryManager manager = CountryManager.getInstance(); 7 | manager.add(new Country("bgn", "Bulgaria", true, 0.2)); 8 | manager.add(new Country("uk", "United Kingdom", false, 0.1)); 9 | 10 | try { 11 | System.out.println(VatTaxCalculator.CalculateTaxFormatted(0.1)); 12 | } catch (NotSupportedCountryException e) { 13 | // TODO Auto-generated catch block 14 | e.printStackTrace(); 15 | } 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /week05/2.Wednesday/VatTaxCalculator/src/NotSupportedCountryException.java: -------------------------------------------------------------------------------- 1 | 2 | public class NotSupportedCountryException extends Exception { 3 | public NotSupportedCountryException(String message) { 4 | super(message); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /week05/2.Wednesday/VatTaxCalculator/src/VatTaxCalculator.java: -------------------------------------------------------------------------------- 1 | 2 | public class VatTaxCalculator { 3 | public static double CalculateTax(double price, String countryCode) throws NotSupportedCountryException { 4 | Country country = CountryManager.getInstance().getCountry(countryCode); 5 | return price * country.getVatTax() + price; 6 | } 7 | 8 | public static double CalculateTax(double price) throws NotSupportedCountryException { 9 | return CalculateTax(price, 10 | CountryManager.getInstance().getDefaultCountryCode()); 11 | } 12 | 13 | public static String CalculateTaxFormatted(double price, String countryCode) throws NotSupportedCountryException { 14 | return String.format("%.2f%s", CalculateTax(price), countryCode); 15 | } 16 | 17 | public static String CalculateTaxFormatted(double price) throws NotSupportedCountryException { 18 | return CalculateTaxFormatted(price, 19 | CountryManager.getInstance().getDefaultCountryCode()); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /week06/1.Wednesday/README.md: -------------------------------------------------------------------------------- 1 | ## Funny array sorter 2 | 3 | Make a FunnyArraySorter class 4 | 5 | It should have a constructor that takes an Integer (pivot) 6 | 7 | It should have several sorting functions using anonymous classes: 8 | #### reverseSort(List list) 9 | 10 | #### pivotSubtractionSort(List list) 11 | 12 | Assume that one Integer is greater than other if it is greater than the second with at lest the pivot value (a>b iff a-pivot>b, a=b iff a-pivot=b) 13 | 14 | #### pivotDivisionSort(List list) 15 | Assume that one Integer is greater than other if when divided by the pivot is greater than the second (a>b iff a/pivot>b, a=b iff a/pivot=b) 16 | 17 | 18 | Bonus: Try to explain why the pivot sorting functions are wrong and will have different result with the same numbers, but reordered. 19 | 20 | 21 | ## User input checker 22 | 23 | Make a UserInputChecker class 24 | 25 | It should have a nested interface Validator which has one function: 26 | public boolean validate(String input) 27 | 28 | create inside the following classes: 29 | 30 | #### PersonNameValidator 31 | #### BulgarianPhoneNumberValidator 32 | #### PersonAgeValidator 33 | #### CreditCardNumberValidator 34 | #### IpVersion4Validator 35 | #### IpVersion6Validator 36 | #### MacAddressValidator 37 | 38 | ## Binary Search Tree 39 | 40 | Create a BST with a Node as nested class. 41 | 42 | You should be able to add, search and remove an element. 43 | You should also calculate the depth and the height of a given element. 44 | 45 | Bonus: Try to calculate the depth and height in O(1). 46 | 47 | If you need help look here: 48 | http://cpp.datastructures.net/presentations/BinarySearchTrees.pdf 49 | 50 | http://stackoverflow.com/questions/2603692/what-is-the-difference-between-tree-depth-and-height -------------------------------------------------------------------------------- /week06/1.Wednesday/prereadings.md: -------------------------------------------------------------------------------- 1 | Take a look at theese links, you can ignore lambda expressions for now we will have special classes for them later. 2 | 3 | https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html 4 | 5 | https://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html 6 | 7 | https://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html 8 | 9 | https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html 10 | 11 | https://docs.oracle.com/javase/tutorial/java/javaOO/whentouse.html -------------------------------------------------------------------------------- /week06/2.Friday/README.md: -------------------------------------------------------------------------------- 1 | ## Bank account 2 | 3 | ### Make a BankAccount class. 4 | 5 | It should have unique number and store information about its and owner - First, Last name and age. 6 | 7 | It should store information about the balance of the account, the interest of the account and the type of the interest (complex and simple year interest). 8 | 9 | If someone tries to create a bank account with invalid information an appropriate exception should be thrown. 10 | 11 | It should support add, withdraw, transfer and history operations. 12 | 13 | When the iterest is greater than 1% the withdraws are forbidden. 14 | 15 | It should remember the last 5 operations of the account. 16 | 17 | ### Make a CLI (Command Line Interpreter) for operating with the Bank accounts 18 | 19 | It should have the following functions: 20 | 21 | * create_bank_account 22 | 23 | It should prompt the user for the needed information and if everything is ok it should create a new bank account. 24 | 25 | * show_history 26 | 27 | It should prompt the user for the bank account number and show its history. 28 | 29 | * add_money 30 | 31 | It should prompt the user for the amount and the bank account number. 32 | 33 | * withdraw_money 34 | 35 | It should prompt the user for the amount and the bank account number. 36 | 37 | * transfer_money 38 | 39 | It should prompt the user for the origin and destination bank account numbers and the amount 40 | 41 | * calculate_amount 42 | 43 | It should prompt the user for bank account number and number of months. 44 | It should return the amount after the given number of months. 45 | 46 | ### The Bank 47 | 48 | It should store the bank accounts. 49 | 50 | ### Notes: 51 | 52 | you should create and use your own custom exceptions: 53 | * InsufficientFundsException 54 | * NonExistingBankAccountException -------------------------------------------------------------------------------- /week06/2.Friday/prereadings.md: -------------------------------------------------------------------------------- 1 | *Exceptions hierarchy in Java* 2 | http://www.javamex.com/tutorials/exceptions/exceptions_hierarchy.shtml 3 | 4 | *Try/catch/finally example* 5 | http://www.tutorialspoint.com/java/java_exceptions.htm 6 | 7 | *Try with resources in Java 7* 8 | http://www.mkyong.com/java/try-with-resources-example-in-jdk-7/ 9 | 10 | *Overriding methods with Exceptions in java* 11 | http://stackoverflow.com/questions/5875414/method-overriding-and-exceptions -------------------------------------------------------------------------------- /week07/1.Monday/Examples/src/FileUtils.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.BufferedWriter; 3 | import java.io.File; 4 | import java.io.FileNotFoundException; 5 | import java.io.FileReader; 6 | import java.io.FileWriter; 7 | import java.io.IOException; 8 | import java.nio.file.Files; 9 | import java.nio.file.Path; 10 | 11 | public class FileUtils { 12 | private FileUtils() { 13 | 14 | } 15 | 16 | private static FileUtils mInstance; 17 | 18 | public static FileUtils getInstance() { 19 | if (mInstance == null) { 20 | mInstance = new FileUtils(); 21 | } 22 | 23 | return mInstance; 24 | } 25 | 26 | public String readFrom(File file) throws IOException { 27 | 28 | BufferedReader buf = null; 29 | StringBuilder builder = new StringBuilder(); 30 | 31 | try { 32 | buf = new BufferedReader(new FileReader(file)); 33 | String line; 34 | 35 | while((line = buf.readLine()) != null) { 36 | builder.append(line); 37 | builder.append(System.lineSeparator()); 38 | } 39 | } 40 | finally { 41 | buf.close(); 42 | } 43 | 44 | return builder.toString(); 45 | } 46 | 47 | public String readFrom(Path path) throws IOException { 48 | return readFrom(path.toFile()); 49 | } 50 | 51 | public void writeTo(String contents, File file) throws IOException { 52 | try (BufferedWriter buf = new BufferedWriter(new FileWriter(file))) { 53 | buf.write(contents); 54 | } 55 | } 56 | 57 | public void writeTo(String contents, Path path) throws IOException { 58 | writeTo(contents, path.toFile()); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /week07/1.Monday/Examples/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedInputStream; 2 | import java.io.BufferedOutputStream; 3 | import java.io.BufferedReader; 4 | import java.io.BufferedWriter; 5 | import java.io.DataInputStream; 6 | import java.io.DataOutputStream; 7 | import java.io.EOFException; 8 | import java.io.File; 9 | import java.io.FileInputStream; 10 | import java.io.FileOutputStream; 11 | import java.io.FileReader; 12 | import java.io.FileWriter; 13 | import java.io.IOException; 14 | import java.io.ObjectInputStream; 15 | import java.io.ObjectOutputStream; 16 | 17 | public class Main { 18 | 19 | /* 20 | * 21 | * Friday 19:00 E-Motion Club 22 | * career event 23 | * 24 | * */ 25 | 26 | static final String dataFile = "invoicedata"; 27 | 28 | static final double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 }; 29 | static final int[] units = { 12, 8, 13, 29, 50 }; 30 | static final String[] descs = { 31 | "Java T-shirt", 32 | "Java Mug", 33 | "Duke Juggling Dolls", 34 | "Java Pin", 35 | "Java Key Chain" 36 | }; 37 | 38 | private static void byteStreams() throws IOException { 39 | FileInputStream in = null; 40 | FileOutputStream out = null; 41 | 42 | try { 43 | in = new FileInputStream("xanadu.txt"); 44 | out = new FileOutputStream("outagain.txt"); 45 | int c; 46 | 47 | while ((c = in.read()) != -1) { 48 | out.write(c); 49 | } 50 | } finally { 51 | if (in != null) { 52 | in.close(); 53 | } 54 | if (out != null) { 55 | out.close(); 56 | } 57 | } 58 | } 59 | 60 | private static void characterStreams() throws IOException { 61 | FileReader inputStream = null; 62 | FileWriter outputStream = null; 63 | 64 | try { 65 | inputStream = new FileReader("xanadu.txt"); 66 | outputStream = new FileWriter("characteroutput.txt"); 67 | 68 | int c; 69 | while ((c = inputStream.read()) != -1) { 70 | outputStream.write(c); 71 | } 72 | } finally { 73 | if (inputStream != null) { 74 | inputStream.close(); 75 | } 76 | if (outputStream != null) { 77 | outputStream.close(); 78 | } 79 | } 80 | } 81 | 82 | private static void bufferedStreams() throws IOException { 83 | BufferedReader inputStream = new BufferedReader(new FileReader("xanadu.txt")); 84 | BufferedWriter outputStream = new BufferedWriter(new FileWriter("characteroutput.txt")); 85 | } 86 | 87 | private static void dataStreams() throws IOException { 88 | DataOutputStream out = new DataOutputStream(new BufferedOutputStream( 89 | new FileOutputStream(dataFile))); 90 | for (int i = 0; i < prices.length; i ++) { 91 | out.writeDouble(prices[i]); 92 | out.writeInt(units[i]); 93 | out.writeUTF(descs[i]); 94 | } 95 | 96 | DataInputStream in = new DataInputStream(new 97 | BufferedInputStream(new FileInputStream(dataFile))); 98 | 99 | double price; 100 | int unit; 101 | String desc; 102 | double total = 0.0; 103 | try { 104 | while (true) { 105 | price = in.readDouble(); 106 | unit = in.readInt(); 107 | desc = in.readUTF(); 108 | System.out.format("You ordered %d" + " units of %s at $%.2f%n", 109 | unit, desc, price); 110 | total += unit * price; 111 | } 112 | } catch (EOFException e) { 113 | } 114 | } 115 | 116 | private static void objectOutputStream() throws IOException { 117 | FileOutputStream fileOutputStream = new FileOutputStream( 118 | "/Users/user/user.txt"); 119 | User user = new User("John", "Sullivan", "myemail@mail.com"); 120 | ObjectOutputStream output = new ObjectOutputStream(fileOutputStream); 121 | try { 122 | output.writeObject(user); 123 | } 124 | finally { 125 | output.close(); 126 | } 127 | } 128 | 129 | private static void objectInputStream() throws IOException { 130 | //Read from the stored file 131 | FileInputStream fileInputStream = new FileInputStream(new File( 132 | "/Users/user/test.txt")); 133 | ObjectInputStream input = new ObjectInputStream(fileInputStream); 134 | User user2; 135 | try { 136 | user2 = (User) input.readObject(); 137 | System.out.println(user2.toString()); 138 | } catch (ClassNotFoundException e) { 139 | e.printStackTrace(); 140 | } 141 | finally { 142 | input.close(); 143 | } 144 | } 145 | 146 | } 147 | -------------------------------------------------------------------------------- /week07/1.Monday/Examples/src/User.java: -------------------------------------------------------------------------------- 1 | import java.io.Serializable; 2 | 3 | public class User implements Serializable { 4 | 5 | /** 6 | * @author anirudh 7 | */ 8 | private static final long serialVersionUID = 8309080721495266420L; 9 | private String firstName; 10 | private String lastName; 11 | private String email; 12 | private transient String fullName; 13 | 14 | public User(String firstName, String lastName, String email) { 15 | super(); 16 | this.firstName = firstName; 17 | this.lastName = lastName; 18 | this.email = email; 19 | this.fullName = firstName + " " + lastName; 20 | } 21 | 22 | //..getters and setters... 23 | 24 | /** 25 | * Two users are equal if their firstName, lastName and email address is 26 | * same. 27 | */ 28 | @Override 29 | public boolean equals(Object obj) { 30 | return (this.firstName.equals(((User) obj).firstName) 31 | && this.lastName.equals(((User) obj).lastName) && this.email 32 | .equals(((User) obj).email)); 33 | } 34 | 35 | @Override 36 | public String toString() { 37 | return this.firstName + " " + this.lastName + " " + this.email; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /week07/1.Monday/prereading.md: -------------------------------------------------------------------------------- 1 | ## Serialization 2 | http://www.tutorialspoint.com/java/java_serialization.htm 3 | https://docs.oracle.com/javase/tutorial/jndi/objects/serial.html 4 | 5 | ## Files 6 | https://docs.oracle.com/javase/tutorial/essential/io/fileio.html (yes, everything) 7 | 8 | ## Input & Output streams 9 | http://www.javatpoint.com/java-io 10 | https://docs.oracle.com/javase/tutorial/essential/io/streams.html (yes, everything) 11 | http://www.tutorialspoint.com/java/java_files_io.htm 12 | -------------------------------------------------------------------------------- /week07/1.Monday/testData.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/week07/1.Monday/testData.zip -------------------------------------------------------------------------------- /week07/2.Wednesday/README.md: -------------------------------------------------------------------------------- 1 | Your task for today is to finish the rest of the problems from Monday. 2 | Use unit tests for the solutions. 3 | **NB: Use unit tests for all of your solutions from now on.** 4 | -------------------------------------------------------------------------------- /week07/2.Wednesday/UnitTestsIntro/src/categories/CategoriesTest.java: -------------------------------------------------------------------------------- 1 | package categories; 2 | 3 | /*import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | import org.junit.experimental.categories.Categories; 7 | import org.junit.experimental.categories.Categories.ExcludeCategory; 8 | import org.junit.experimental.categories.Categories.IncludeCategory; 9 | import org.junit.experimental.categories.Category; 10 | import org.junit.runner.RunWith; 11 | import org.junit.runners.Suite.SuiteClasses; 12 | 13 | public class A { 14 | @Test 15 | public void a() { 16 | fail(); 17 | } 18 | 19 | @Category(SlowTests.class) 20 | @Test 21 | public void b() { 22 | } 23 | } 24 | 25 | @Category({ SlowTests.class, FastTests.class }) 26 | public class B { 27 | @Test 28 | public void c() { 29 | } 30 | } 31 | 32 | @RunWith(Categories.class) 33 | @IncludeCategory(SlowTests.class) 34 | @SuiteClasses({ A.class, B.class }) 35 | // Note that Categories is a kind of Suite 36 | public class SlowTestSuite1 { 37 | // Will run A.b and B.c, but not A.a 38 | } 39 | 40 | @RunWith(Categories.class) 41 | @IncludeCategory(SlowTests.class) 42 | @ExcludeCategory(FastTests.class) 43 | @SuiteClasses({ A.class, B.class }) 44 | // Note that Categories is a kind of Suite 45 | public class SlowTestSuite2 { 46 | // Will run A.b, but not A.a or B.c 47 | } */ 48 | 49 | -------------------------------------------------------------------------------- /week07/2.Wednesday/UnitTestsIntro/src/categories/FastTests.java: -------------------------------------------------------------------------------- 1 | package categories; 2 | 3 | public interface FastTests { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /week07/2.Wednesday/UnitTestsIntro/src/categories/SlowTests.java: -------------------------------------------------------------------------------- 1 | package categories; 2 | 3 | public interface SlowTests { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /week07/2.Wednesday/UnitTestsIntro/src/fibonacci/Fibonacci.java: -------------------------------------------------------------------------------- 1 | package fibonacci; 2 | 3 | public class Fibonacci { 4 | public static int compute(int n) { 5 | if (n <= 1) return n; 6 | else return compute(n-1) + compute(n-2); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /week07/2.Wednesday/UnitTestsIntro/src/fibonacci/FibonacciTest.java: -------------------------------------------------------------------------------- 1 | package fibonacci; 2 | import static org.junit.Assert.*; 3 | 4 | import java.util.Arrays; 5 | import java.util.Collection; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.junit.runners.Parameterized; 10 | import org.junit.runners.Parameterized.Parameters; 11 | 12 | @RunWith(Parameterized.class) 13 | public class FibonacciTest { 14 | 15 | // [0: fib(0)=0](0.000 s) 16 | // [1: fib(1)=1](0.000 s) 17 | // [2: fib(2)=1](0.000 s) 18 | 19 | @Parameters(name = "{index}: fib({0})={1}") 20 | public static Collection data() { 21 | return Arrays.asList(new Object[][] { 22 | // 0 1 1 2 3 5 8 23 | { 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } 24 | }); 25 | } 26 | 27 | private int fInput; 28 | private int fExpected; 29 | 30 | public FibonacciTest(int input, int expected) { 31 | fInput= input; 32 | fExpected= expected; 33 | System.out.println("FibonacciTest " + fInput + " " + fExpected + " " + this); 34 | } 35 | 36 | @Test 37 | public void test() { 38 | assertEquals(fExpected, Fibonacci.compute(fInput)); 39 | } 40 | } -------------------------------------------------------------------------------- /week07/2.Wednesday/UnitTestsIntro/src/simple/DemoTest.java: -------------------------------------------------------------------------------- 1 | package simple; 2 | 3 | import org.junit.Assert; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | import org.junit.Test; 8 | 9 | public class DemoTest { 10 | 11 | @Test 12 | public void testAdd() { 13 | SimpleCalculator calc = new SimpleCalculator(); 14 | int expected = 8; 15 | int actual = calc.add(6, 2); 16 | assertEquals("Test if addition works.", expected, actual); 17 | } 18 | 19 | @Test 20 | public void testSubtract() { 21 | fail("Not yet implemented"); 22 | } 23 | 24 | @Test 25 | public void testDivide() { 26 | fail("Not yet implemented"); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /week07/2.Wednesday/UnitTestsIntro/src/simple/SimpleCalculator.java: -------------------------------------------------------------------------------- 1 | package simple; 2 | 3 | public class SimpleCalculator { 4 | public int add(int a, int b) { 5 | return a+b; 6 | } 7 | 8 | public int subtract(int a, int b) { 9 | return a-b; 10 | } 11 | 12 | public double divide(double a, double b) { 13 | if (b == 0) { 14 | throw new IllegalArgumentException("Divisor cannot be 0."); 15 | } 16 | 17 | return a/b; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /week07/2.Wednesday/UnitTestsIntro/src/simple/SimpleCalculatorTest.java: -------------------------------------------------------------------------------- 1 | package simple; 2 | import static org.junit.Assert.*; 3 | 4 | import org.junit.AfterClass; 5 | import org.junit.Before; 6 | import org.junit.BeforeClass; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.junit.runners.Parameterized; 10 | 11 | public class SimpleCalculatorTest { 12 | 13 | @Test 14 | public void testAdd() { 15 | assertEquals("Test if addition works.", 7, mCalc.add(2, 5)); 16 | } 17 | 18 | @Test 19 | public void testSubtract() { 20 | assertEquals("Test if subtraction works.", 4, mCalc.subtract(8, 4)); 21 | } 22 | 23 | @Test 24 | public void testDivision() { 25 | assertEquals(4.5, mCalc.divide(9, 2), 0.0001); 26 | } 27 | 28 | @Test (expected = IllegalArgumentException.class) 29 | public void testCatchesZeroDivision() { 30 | mCalc.divide(2, 0); 31 | } 32 | 33 | private static SimpleCalculator mCalc; 34 | 35 | @BeforeClass 36 | public static void initCalculator() { 37 | mCalc = new SimpleCalculator(); 38 | } 39 | 40 | @AfterClass 41 | public static void destroyCalculator() { 42 | mCalc = null; 43 | } 44 | 45 | @Before 46 | public static void initBeforeCalculator() { 47 | // called before EACH TEST 48 | } 49 | 50 | 51 | } 52 | -------------------------------------------------------------------------------- /week07/2.Wednesday/UnitTestsIntro/src/suits/A.java: -------------------------------------------------------------------------------- 1 | package suits; 2 | 3 | public class A { 4 | public void methodA() { 5 | 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /week07/2.Wednesday/UnitTestsIntro/src/suits/ABTest.java: -------------------------------------------------------------------------------- 1 | package suits; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.junit.runners.Suite; 8 | import org.junit.runners.Suite.SuiteClasses; 9 | 10 | @RunWith(Suite.class) 11 | @SuiteClasses ({ATest.class, BTest.class}) 12 | public class ABTest { 13 | 14 | } 15 | -------------------------------------------------------------------------------- /week07/2.Wednesday/UnitTestsIntro/src/suits/ATest.java: -------------------------------------------------------------------------------- 1 | package suits; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | public class ATest { 8 | 9 | @Test 10 | public void testA() { 11 | assert(true); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /week07/2.Wednesday/UnitTestsIntro/src/suits/B.java: -------------------------------------------------------------------------------- 1 | package suits; 2 | 3 | public class B { 4 | public void methodB() { 5 | 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /week07/2.Wednesday/UnitTestsIntro/src/suits/BTest.java: -------------------------------------------------------------------------------- 1 | package suits; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Test; 6 | 7 | public class BTest { 8 | 9 | @Test 10 | public void testB() { 11 | fail("Not yet implemented"); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /week07/2.Wednesday/prereading.md: -------------------------------------------------------------------------------- 1 | ### Testing levels 2 | https://en.wikipedia.org/wiki/Software_testing#Testing_levels 3 | 4 | ### Testing methods 5 | https://en.wikipedia.org/wiki/Software_testing#Testing_methods 6 | 7 | ### JUnit 8 | http://junit.sourceforge.net/doc/cookbook/cookbook.htm 9 | http://www.vogella.com/tutorials/JUnit/article.html 10 | https://www.youtube.com/watch?v=SW9qetnQ0XE 11 | 12 | -------------------------------------------------------------------------------- /week08/1.Monday/1-Peer-Review/GroupMatcher/.idea/.name: -------------------------------------------------------------------------------- 1 | GroupMatcher -------------------------------------------------------------------------------- /week08/1.Monday/1-Peer-Review/GroupMatcher/.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /week08/1.Monday/1-Peer-Review/GroupMatcher/.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /week08/1.Monday/1-Peer-Review/GroupMatcher/.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /week08/1.Monday/1-Peer-Review/GroupMatcher/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 1.8 31 | 32 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /week08/1.Monday/1-Peer-Review/GroupMatcher/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /week08/1.Monday/1-Peer-Review/GroupMatcher/GroupMatcher.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /week08/1.Monday/1-Peer-Review/GroupMatcher/out/production/GroupMatcher/Main.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/week08/1.Monday/1-Peer-Review/GroupMatcher/out/production/GroupMatcher/Main.class -------------------------------------------------------------------------------- /week08/1.Monday/1-Peer-Review/GroupMatcher/out/production/GroupMatcher/org/hackbulgaria/Matcher.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/week08/1.Monday/1-Peer-Review/GroupMatcher/out/production/GroupMatcher/org/hackbulgaria/Matcher.class -------------------------------------------------------------------------------- /week08/1.Monday/1-Peer-Review/GroupMatcher/out/production/GroupMatcher/org/hackbulgaria/Pair.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/week08/1.Monday/1-Peer-Review/GroupMatcher/out/production/GroupMatcher/org/hackbulgaria/Pair.class -------------------------------------------------------------------------------- /week08/1.Monday/1-Peer-Review/GroupMatcher/out/production/GroupMatcher/org/hackbulgaria/Person.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/week08/1.Monday/1-Peer-Review/GroupMatcher/out/production/GroupMatcher/org/hackbulgaria/Person.class -------------------------------------------------------------------------------- /week08/1.Monday/1-Peer-Review/GroupMatcher/people.txt: -------------------------------------------------------------------------------- 1 | Hristo Kirilov 2 | Angelo Petkov 3 | Ivan Atanasov 4 | Borislav Borislavov 5 | Georgi Dankov 6 | Georgi Pavlov 7 | Stefan Dimitrov 8 | Vasil Trifonov 9 | Tsvetomir Stoimenov 10 | Ivan Petrov 11 | Georgi Arnaudov 12 | Veneta Dimitrova 13 | Nikola Tsolov 14 | Polina Krusteva 15 | Ivan Mehandjiev 16 | Krasimir Iliev 17 | Veronika Radenkova 18 | Martin Yordanov 19 | Tsvetan Datsev 20 | Angel Angelov 21 | Boyko Lalov 22 | Mariana Partsaleva 23 | Tonka Jeleva 24 | Elizabet Staneva 25 | Mihaela Karaivanova 26 | Mihail Tsonev 27 | Vasil Vasilev 28 | Plamen Neshkov 29 | -------------------------------------------------------------------------------- /week08/1.Monday/1-Peer-Review/GroupMatcher/src/Main.java: -------------------------------------------------------------------------------- 1 | import org.hackbulgaria.Matcher; 2 | 3 | import java.io.IOException; 4 | 5 | public class Main { 6 | public static void main(String[] args) throws IOException { 7 | Matcher groupMatcher = new Matcher("people.txt", 5); 8 | groupMatcher.getRotation(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /week08/1.Monday/1-Peer-Review/GroupMatcher/src/org/hackbulgaria/Matcher.java: -------------------------------------------------------------------------------- 1 | package org.hackbulgaria; 2 | 3 | import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils; 4 | 5 | import java.io.BufferedReader; 6 | import java.io.FileReader; 7 | import java.io.IOException; 8 | import java.nio.file.Path; 9 | import java.nio.file.Paths; 10 | import java.util.*; 11 | 12 | /** 13 | * Created by plamen on 1/18/16. 14 | */ 15 | public class Matcher { 16 | private final int mRotations; 17 | private final Path mPeoplePath; 18 | private List mPeople; 19 | private Set mPairedPeople; 20 | 21 | public Matcher(String peoplePath, int rotations) throws IOException { 22 | mPeoplePath = Paths.get(peoplePath); 23 | mRotations = rotations; 24 | mPeople = getPeople(); 25 | mPairedPeople = new HashSet<>(); 26 | } 27 | 28 | private List getPeople() throws IOException { 29 | List people = new ArrayList<>(); 30 | 31 | try (BufferedReader reader = new BufferedReader(new FileReader(mPeoplePath.toFile()))) { 32 | String line; 33 | while ((line = reader.readLine()) != null) { 34 | String[] args = line.split("\\s+"); 35 | Person newPerson = new Person(args[0], args[1]); 36 | people.add(newPerson); 37 | } 38 | } 39 | 40 | return people; 41 | } 42 | 43 | private int getPersonIndex() { 44 | Random random = new Random(); 45 | 46 | int index; 47 | do { 48 | index = random.nextInt(mPeople.size()); 49 | } while (mPairedPeople.contains(index)); 50 | mPairedPeople.add(index); 51 | 52 | return index; 53 | } 54 | 55 | public void getRotation() throws IOException { 56 | List pairs = new ArrayList<>(); 57 | while (mPairedPeople.size() < mPeople.size()) { 58 | Person personA = mPeople.get(getPersonIndex()); 59 | Person personB = mPeople.get(getPersonIndex()); 60 | 61 | Pair newPair = new Pair(personA, personB); 62 | pairs.add(newPair); 63 | } 64 | for (Pair pair : pairs) { 65 | System.out.println(pair); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /week08/1.Monday/1-Peer-Review/GroupMatcher/src/org/hackbulgaria/Pair.java: -------------------------------------------------------------------------------- 1 | package org.hackbulgaria; 2 | 3 | /** 4 | * Created by plamen on 1/18/16. 5 | */ 6 | public class Pair { 7 | private final Person mPersonA; 8 | private final Person mPersonB; 9 | 10 | public Pair(Person personA, Person personB) { 11 | mPersonA = personA; 12 | mPersonB = personB; 13 | } 14 | 15 | @Override 16 | public String toString() { 17 | return String.format("* Pair(%s, %s)", mPersonA, mPersonB); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /week08/1.Monday/1-Peer-Review/GroupMatcher/src/org/hackbulgaria/Person.java: -------------------------------------------------------------------------------- 1 | package org.hackbulgaria; 2 | 3 | /** 4 | * Created by plamen on 1/18/16. 5 | */ 6 | public class Person { 7 | private final String mFirstName; 8 | private final String mLastName; 9 | 10 | public Person(String firstName, String lastName) { 11 | mFirstName = firstName; 12 | mLastName = lastName; 13 | } 14 | 15 | public String getFirstName() { 16 | return mFirstName; 17 | } 18 | 19 | public String getLastName() { 20 | return mLastName; 21 | } 22 | 23 | @Override 24 | public String toString() { 25 | return String.format("%s %s", mFirstName, mLastName); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /week08/1.Monday/1-Peer-Review/README.md: -------------------------------------------------------------------------------- 1 | # Peer Review 2 | 3 | Your task for today is not about writing code. It is about looking at code & improving it. 4 | 5 | Using the knowledge we have from [the prereading](../prereading.md), do the following: 6 | 7 | 1. Split into groups of 2. 8 | 2. Both of you - pick a problem of your choice. 9 | 3. Conduct a peer review. Lets say we have two peers `A` and `B`. 10 | * `A` should look, comment & suggest improvements for `B`'s code. 11 | * `B` should do the same for A's code. 12 | 4. Whenever there are suggestions for improvements, make a pull request. (This means, that `A` should fork `B`'s code repo and vice versa) 13 | 14 | We are going to make 5 rotations with different groups. 15 | 16 | Peer reviews are essential for learning! 17 | -------------------------------------------------------------------------------- /week08/1.Monday/1-Peer-Review/rotations.md: -------------------------------------------------------------------------------- 1 | ## Rotation 1 2 | 3 | * Pair(Martin Yordanov, Tonka Jeleva) 4 | * Pair(Mihaela Karaivanova, Tsvetan Datsev) 5 | * Pair(Boyko Lalov, Ivan Petrov) 6 | * Pair(Georgi Dankov, Krasimir Iliev) 7 | * Pair(Georgi Pavlov, Mihail Tsonev) 8 | * Pair(Mariana Partsaleva, Veneta Dimitrova) 9 | * Pair(Veronika Radenkova, Nikola Tsolov) 10 | * Pair(Georgi Arnaudov, Plamen Neshkov) 11 | * Pair(Tsvetomir Stoimenov, Stefan Dimitrov) 12 | * Pair(Ivan Mehandjiev, Vasil Trifonov) 13 | * Pair(Hristo Kirilov, Borislav Borislavov) 14 | * Pair(Angelo Petkov, Elizabet Staneva) 15 | * Pair(Angel Angelov, Vasil Vasilev) 16 | * Pair(Polina Krusteva, Ivan Atanasov) 17 | 18 | ## Rotation 2 19 | 20 | * Pair(Elizabet Staneva, Hristo Kirilov) 21 | * Pair(Georgi Arnaudov, Polina Krusteva) 22 | * Pair(Vasil Vasilev, Borislav Borislavov) 23 | * Pair(Ivan Mehandjiev, Tsvetomir Stoimenov) 24 | * Pair(Mihail Tsonev, Veneta Dimitrova) 25 | * Pair(Krasimir Iliev, Ivan Petrov) 26 | * Pair(Nikola Tsolov, Ivan Atanasov) 27 | * Pair(Tonka Jeleva, Tsvetan Datsev) 28 | * Pair(Mihaela Karaivanova, Stefan Dimitrov) 29 | * Pair(Boyko Lalov, Martin Yordanov) 30 | * Pair(Georgi Dankov, Plamen Neshkov) 31 | * Pair(Angel Angelov, Angelo Petkov) 32 | * Pair(Vasil Trifonov, Georgi Pavlov) 33 | * Pair(Veronika Radenkova, Mariana Partsaleva) 34 | 35 | ## Rotation 3 36 | 37 | * Pair(Mihail Tsonev, Krasimir Iliev) 38 | * Pair(Georgi Pavlov, Georgi Arnaudov) 39 | * Pair(Ivan Mehandjiev, Angel Angelov) 40 | * Pair(Angelo Petkov, Tsvetan Datsev) 41 | * Pair(Boyko Lalov, Vasil Vasilev) 42 | * Pair(Mihaela Karaivanova, Georgi Dankov) 43 | * Pair(Martin Yordanov, Nikola Tsolov) 44 | * Pair(Ivan Petrov, Mariana Partsaleva) 45 | * Pair(Plamen Neshkov, Polina Krusteva) 46 | * Pair(Veronika Radenkova, Elizabet Staneva) 47 | * Pair(Veneta Dimitrova, Hristo Kirilov) 48 | * Pair(Tsvetomir Stoimenov, Ivan Atanasov) 49 | * Pair(Tonka Jeleva, Vasil Trifonov) 50 | * Pair(Borislav Borislavov, Stefan Dimitrov) 51 | 52 | ## Rotation 4 53 | 54 | * Pair(Georgi Pavlov, Elizabet Staneva) 55 | * Pair(Veneta Dimitrova, Georgi Arnaudov) 56 | * Pair(Mihaela Karaivanova, Tsvetan Datsev) 57 | * Pair(Angel Angelov, Vasil Trifonov) 58 | * Pair(Hristo Kirilov, Angelo Petkov) 59 | * Pair(Ivan Petrov, Tonka Jeleva) 60 | * Pair(Nikola Tsolov, Plamen Neshkov) 61 | * Pair(Ivan Atanasov, Tsvetomir Stoimenov) 62 | * Pair(Vasil Vasilev, Veronika Radenkova) 63 | * Pair(Krasimir Iliev, Stefan Dimitrov) 64 | * Pair(Mihail Tsonev, Mariana Partsaleva) 65 | * Pair(Borislav Borislavov, Martin Yordanov) 66 | * Pair(Ivan Mehandjiev, Georgi Dankov) 67 | * Pair(Boyko Lalov, Polina Krusteva) 68 | 69 | ## Rotation 5 70 | 71 | * Pair(Tsvetomir Stoimenov, Tonka Jeleva) 72 | * Pair(Plamen Neshkov, Hristo Kirilov) 73 | * Pair(Vasil Trifonov, Boyko Lalov) 74 | * Pair(Nikola Tsolov, Stefan Dimitrov) 75 | * Pair(Elizabet Staneva, Mihail Tsonev) 76 | * Pair(Georgi Dankov, Veronika Radenkova) 77 | * Pair(Angel Angelov, Georgi Pavlov) 78 | * Pair(Polina Krusteva, Mariana Partsaleva) 79 | * Pair(Vasil Vasilev, Ivan Mehandjiev) 80 | * Pair(Ivan Atanasov, Mihaela Karaivanova) 81 | * Pair(Angelo Petkov, Tsvetan Datsev) 82 | * Pair(Krasimir Iliev, Ivan Petrov) 83 | * Pair(Borislav Borislavov, Georgi Arnaudov) 84 | * Pair(Veneta Dimitrova, Martin Yordanov) 85 | -------------------------------------------------------------------------------- /week08/1.Monday/prereading.md: -------------------------------------------------------------------------------- 1 | * What is PMD? https://en.wikipedia.org/wiki/PMD_(software) 2 | * PMD with Eclipse tutorial: http://www.javatips.net/blog/2012/06/pmd-in-eclipse-tutorial 3 | * PMD with Eclipse video tutorial: https://www.youtube.com/watch?v=2h68dWYHQb0 4 | * Static code analysis http://searchwindevelopment.techtarget.com/definition/static-analysis 5 | * Dynamic code analysis http://istqbexamcertification.com/what-is-dynamic-analysis-tools-in-software-testing/ 6 | * Static vs Dynamic code analysis https://gcn.com/articles/2009/02/09/static-vs-dynamic-code-analysis.aspx 7 | * Github pull requests https://help.github.com/articles/using-pull-requests/ 8 | * Github Flow https://guides.github.com/introduction/flow/ 9 | * Reviews https://www.lullabot.com/articles/the-peer-review-howto-guide 10 | -------------------------------------------------------------------------------- /week08/2.Friday/README.md: -------------------------------------------------------------------------------- 1 | ## Welcome to the mystic world of multithreading 2 | 3 | ### 1. Make a simple Thread class that prints a message. 4 | 5 | ### 2. Make a simple Runnable class that prints a message. 6 | 7 | ### 2. Use one of the previously implemented classes and now print something from the main thread. 8 | Now try using .join() before printing the message from the main class. 9 | 10 | ### 3. Make Thread that sums two integers provided from the user. 11 | 12 | ### 4. Lost update example. Make two threads that increment the same counter 1 000 000 times. What is the result? Why this problem exists? How can we resolve it? 13 | Hint: synchronized, atomic classes 14 | 15 | ### 5. Try to reproduce Visibility problem. 16 | -------------------------------------------------------------------------------- /week08/2.Friday/prereading.md: -------------------------------------------------------------------------------- 1 | *Oracle's concurency trail* 2 | http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html 3 | *Q&A* 4 | * What is the difference between process and thread? 5 | * What is Runnable? Whats is Tread? 6 | * What are the most important methods in Thread ? 7 | * What is starvation, livelock and deadlock ? 8 | * What is thread interference and memory consistency errors ? 9 | * What is intrinsic lock ? 10 | 11 | *Multithreading example* 12 | http://www.tutorialspoint.com/java/java_multithreading.htm 13 | -------------------------------------------------------------------------------- /week09/1.Monday/README.md: -------------------------------------------------------------------------------- 1 | ### Implement a simple blocking queue. 2 | A blocking queue is just like a regular queue, with the difference that if someone calls `poll()` and the queue is empty, the call is blocked until somebody adds an element to the queue. After an element is added, the caller (the one who called `poll()`) gets unblocked and the `poll()` call returns. 3 | 4 | ### Bonus: 5 | Introduce classical very common interview scenario *Producer - Consumer problem*. Create several threads (Producers) that only produce `add(E e)` in your queue and several threads (Consumers) that only consume `poll()` from your queue. Your blocking queue should have a max size. When a max size is reached all producers are halted until some object have been consumed. 6 | 7 | ### Parallel minimal point calculations 8 | 9 | Create a static method `generatePoints()` which returns a `List` - `create your Point impl (with maybe different implementations)` 10 | Implement it, generating a 100 000 points (in java that is written `100_000`) points with random coordinates - ranging from 0 to 10_000. 11 | 12 | Now, for each of those points, I'd like you to find it's nearest point. Do this in a method `Map getNearestPoints(List generatedPoints)` 13 | 14 | It takes a while. By calculations, it should take like lots of seconds to complete (depending on your CPU speed). 15 | 16 | Now introduce some multithreading to speed it up. 17 | Declare and implement a method `doCalculations(List inPoints, int indexFrom, int indexTo, Map outMap)`. 18 | Move calculations logic from `getNearestPoints` to `doCalculations`, but work strictly from `indexFrom`, to `indexTo`. 19 | 20 | Now in `getNearestPoints(List generatedPoints)` method, start two Threads that call `doCalculations`, in their run methods, one from 0 to half of the elements, the other from half of the elements to the last of them. 21 | 22 | Measure speedup between the two implementations (See `System.currentTimeMillis()`). 23 | 24 | Introduce a third and forth thread. Does your implementation go faster? 25 | 26 | Think how to generalize the number of threads and how to implement it. 27 | 28 | ### Bulk Thumbnail Creator 29 | Picture processing can take a bit of time for some transformations. Especially if the image is large. Create an image program which can take a directory path and converts all images in it and its subdirectories to a specified size in the background thread while you do other things. For each directory, you should create a `thumbnails` directory and store the new thumbnails there. It should work like a console application, taking an argument for the directory and for the new thumbnail size. 30 | 31 | Example usage: `java thumbnailGen /home/pesho/Desktop/pics/ 150 150` 32 | This should generate thumbnails in /home/pesho/Desktop/pics/thumbnails/ with size 150x150 px. 33 | 34 | **BONUS:** Handle the resizing in one thread and bulk renaming of thumbnails in another thread. 35 | **BONUS 2:** Add an option whether to include the images in the subdirectories (e.g. whether it should be recursive or not). For example, `java thumbnailGen -r /home/pesho/Desktop/pics/ 150 150` should do it recursively. 36 | 37 | ### Parallel Copy 38 | Create a java tool which copies a source folder with all its files and subfolders to a target folder. The twist is to make the program intelligent enough to perform several copies in parallel. It should take into account the file sizes and the number of files. For example, if you copy 8 small files, the program can decide to copy them on one thread. If they are 16, it can copy them on 2 threads. If you copy 1 big file and 3 small files, it can copy the big file on a separate thread. It is up to you how it makes these decisions. It should work like a console application, taking as arguments the source and target directory. Add an option which specifies whether to use this optimization* or not (for example, if you add -s, you make a regular copy without creating new threads). 39 | 40 | Example usage: `java cp /home/pesho/Desktop/source/ /home/pesho/Desktop/target/` 41 | This should copy all files from /home/pesho/Desktop/source/ to /home/pesho/Desktop/target/ 42 | 43 | *Is it actually an optimization? Try your program with some big files with -s and without -s. Do you see a noticable difference? Can you explain why so? 44 | -------------------------------------------------------------------------------- /week09/1.Monday/prereading.md: -------------------------------------------------------------------------------- 1 | We will continue talking about threading in Java. 2 | 3 | Read everything from Liveness onwards: http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html 4 | -------------------------------------------------------------------------------- /week09/2.Wednesday/README.md: -------------------------------------------------------------------------------- 1 | ### 1. Declare an annotation type 'ClassInfo' ### 2 | It should contain information about: 3 | - author of the class 4 | - revision of the class (by default it should be 1) 5 | - should the class be 'checked' (by default it should be) //this 'checked' thing is a bogus one, I just made it up so you can use a boolean default 6 | - an array of 'related' classes (Class[]) 7 | 8 | - Annotatate a class with this annotation. Fill in the 'required' information 9 | - In a main method, instantiate the annotated class. Using the `getClass().getAnnotations()`, print out all the annotations declared for your annotated class. 10 | - Now fetch your own annotation using `yourInstance.getClass().getAnnotation(YourAnnotationName.class);` 11 | - Print out all the filled information 12 | 13 | ### 2. JUnit ### 14 | Write an implementation of JUnit framework yourself 15 | -------------------------------------------------------------------------------- /week09/2.Wednesday/prereading.md: -------------------------------------------------------------------------------- 1 | *Annotation & Reflection + example* 2 | * http://tutorials.jenkov.com/java-reflection/index.html 3 | * http://tutorials.jenkov.com/java/annotations.html 4 | 5 | *Long version of explanations* 6 | * http://docs.oracle.com/javase/tutorial/java/annotations/ 7 | * http://docs.oracle.com/javase/tutorial/reflect/ 8 | -------------------------------------------------------------------------------- /week09/3.Friday/README.md: -------------------------------------------------------------------------------- 1 | ### Implement a simple blocking queue. 2 | A blocking queue is just like a regular queue, with the difference that if someone calls `poll()` and the queue is empty, the call is blocked until somebody adds an element to the queue. After an element is added, the caller (the one who called `poll()`) gets unblocked and the `poll()` call returns. 3 | 4 | ### Bonus: 5 | Introduce classical very common interview scenario *Producer - Consumer problem*. Create several threads (Producers) that only produce `add(E e)` in your queue and several threads (Consumers) that only consume `poll()` from your queue. Your blocking queue should have a max size. When a max size is reached all producers are halted until some object have been consumed. 6 | 7 | ### Parallel minimal point calculations 8 | 9 | Create a static method `generatePoints()` which returns a `List` - `create your Point impl (with maybe different implementations)` 10 | Implement it, generating a 100 000 points (in java that is written `100_000`) points with random coordinates - ranging from 0 to 10_000. 11 | 12 | Now, for each of those points, I'd like you to find it's nearest point. Do this in a method `Map getNearestPoints(List generatedPoints)` 13 | 14 | It takes a while. By calculations, it should take like lots of seconds to complete (depending on your CPU speed). 15 | 16 | Now introduce some multithreading to speed it up. 17 | Declare and implement a method `doCalculations(List inPoints, int indexFrom, int indexTo, Map outMap)`. 18 | Move calculations logic from `getNearestPoints` to `doCalculations`, but work strictly from `indexFrom`, to `indexTo`. 19 | 20 | Now in `getNearestPoints(List generatedPoints)` method, start two Threads that call `doCalculations`, in their run methods, one from 0 to half of the elements, the other from half of the elements to the last of them. 21 | 22 | Measure speedup between the two implementations (See `System.currentTimeMillis()`). 23 | 24 | Introduce a third and forth thread. Does your implementation go faster? 25 | 26 | Think how to generalize the number of threads and how to implement it. 27 | 28 | ### Bulk Thumbnail Creator 29 | Picture processing can take a bit of time for some transformations. Especially if the image is large. Create an image program which can take a directory path and converts all images in it and its subdirectories to a specified size in the background thread while you do other things. For each directory, you should create a `thumbnails` directory and store the new thumbnails there. It should work like a console application, taking an argument for the directory and for the new thumbnail size. 30 | 31 | Example usage: `java thumbnailGen /home/pesho/Desktop/pics/ 150 150` 32 | This should generate thumbnails in /home/pesho/Desktop/pics/thumbnails/ with size 150x150 px. 33 | 34 | **BONUS:** Handle the resizing in one thread and bulk renaming of thumbnails in another thread. 35 | **BONUS 2:** Add an option whether to include the images in the subdirectories (e.g. whether it should be recursive or not). For example, `java thumbnailGen -r /home/pesho/Desktop/pics/ 150 150` should do it recursively. 36 | 37 | ### Parallel Copy 38 | Create a java tool which copies a source folder with all its files and subfolders to a target folder. The twist is to make the program intelligent enough to perform several copies in parallel. It should take into account the file sizes and the number of files. For example, if you copy 8 small files, the program can decide to copy them on one thread. If they are 16, it can copy them on 2 threads. If you copy 1 big file and 3 small files, it can copy the big file on a separate thread. It is up to you how it makes these decisions. It should work like a console application, taking as arguments the source and target directory. Add an option which specifies whether to use this optimization* or not (for example, if you add -s, you make a regular copy without creating new threads). 39 | 40 | Example usage: `java cp /home/pesho/Desktop/source/ /home/pesho/Desktop/target/` 41 | This should copy all files from /home/pesho/Desktop/source/ to /home/pesho/Desktop/target/ 42 | 43 | *Is it actually an optimization? Try your program with some big files with -s and without -s. Do you see a noticable difference? Can you explain why so? 44 | 45 | 46 | ### Reimplement atomic int with Lock objects - test and measure performance 47 | 48 | ### Paralel web crawler 49 | 50 | There is a bottleneck in web crawling - while waiting for an answer from the server, the CPU does nothing. 51 | It would be better to make several requests at once. 52 | 53 | Try to crawl 9gag.com, for instance, and print every page you've visited. See the speed is not that great. 54 | Now Introduce parallelisation and speed up the solution. Use an approach similiar to the approach for task #1. 55 | 56 | If your web crawler project is not working, use the one in this github folder instead. (It's a Maven project, you will need to fetch all dependencies). 57 | 58 | 59 | ### Multiply Matrices 60 | Use the solution you did in the OOP lecture and add functionality to multiply two matrices - think about OOP decision to implement it - think how to speed it up, then measure how faster it is and also measure if CPU is allocated enough. (Team -- design) 61 | -------------------------------------------------------------------------------- /week09/3.Friday/prereading.md: -------------------------------------------------------------------------------- 1 | High Concurrency details and tricks 2 | * https://docs.oracle.com/javase/tutorial/essential/concurrency/highlevel.html 3 | 4 | *Books (that are considered the Bibles)* 5 | - Java Concurrency in Practice by Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, and Doug Lea. 6 | - Concurrent Programming in Java: Design Principles and Pattern (2nd Edition) by Doug Lea, the architect of the Java platform's concurrency framework. 7 | 8 | *Lars Vogel's threading tutorial* 9 | http://www.vogella.com/tutorials/JavaConcurrency/article.html#forkjoin 10 | -------------------------------------------------------------------------------- /week10/1.Monday/prereading.md: -------------------------------------------------------------------------------- 1 | Important to read 2 | * https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html 3 | * https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html 4 | * http://tutorials.jenkov.com/java-concurrency/locks.html 5 | * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/StampedLock.html 6 | * https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html 7 | * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html 8 | * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html 9 | * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html 10 | * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Callable.html 11 | * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html 12 | * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html 13 | * https://www.securecoding.cert.org/confluence/display/java/THI03-J.+Always+invoke+wait()+and+await()+methods+inside+a+loop 14 | 15 | High Concurrency details and tricks 16 | * https://docs.oracle.com/javase/tutorial/essential/concurrency/highlevel.html 17 | 18 | *Books (that are considered for bibles)* 19 | - Java Concurrency in Practice by Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, and Doug Lea. 20 | - Concurrent Programming in Java: Design Principles and Pattern (2nd Edition) by Doug Lea, the architect of the Java platform's concurrency framework. 21 | 22 | *Lars Vogel's threading tutorial* 23 | http://www.vogella.com/tutorials/JavaConcurrency/article.html#forkjoin 24 | -------------------------------------------------------------------------------- /week10/1.Monday/producer_consumer/ProducerConsumer.java: -------------------------------------------------------------------------------- 1 | package producer_consumer; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class ProducerConsumer { 7 | 8 | public static void main(String[] args) throws Exception { 9 | Memory memory = new Memory(100); 10 | Producer p= new Producer(memory); 11 | Consumer pp= new Consumer(memory); 12 | Consumer ppp= new Consumer(memory); 13 | Thread t = new Thread(p); 14 | Thread tt = new Thread(pp); 15 | Thread ttt = new Thread(ppp); 16 | t.start(); 17 | tt.start(); 18 | ttt.start(); 19 | t.join(); 20 | tt.join(); 21 | 22 | System.out.println("dsadas"); 23 | System.out.println("dsadas");System.out.println("dsadas"); 24 | System.out.println("dsadas");System.out.println("dsadas"); 25 | System.out.println("dsadas"); 26 | 27 | } 28 | 29 | static class Producer implements Runnable { 30 | int count = 0; 31 | Memory m; 32 | 33 | public Producer(Memory m) { 34 | this.m = m; 35 | } 36 | 37 | @Override 38 | public void run() { 39 | // TODO Auto-generated method stub 40 | while(true) { 41 | try { 42 | // Thread.sleep(100); 43 | m.put(++count); 44 | System.out.println("Produced " + count + " " + Thread.currentThread().getName()); 45 | } catch (InterruptedException e) { 46 | e.printStackTrace(); 47 | } 48 | } 49 | } 50 | } 51 | 52 | static class Consumer implements Runnable { 53 | Memory m; 54 | 55 | public Consumer(Memory m) { 56 | this.m = m; 57 | } 58 | 59 | @Override 60 | public void run() { 61 | // TODO Auto-generated method stub 62 | while(true) { 63 | try { 64 | // Thread.sleep(110); 65 | Object result = m.get(); 66 | System.out.println("Consumed " + result + " " + Thread.currentThread().getName()); 67 | } catch (InterruptedException e) { 68 | e.printStackTrace(); 69 | } 70 | 71 | } 72 | } 73 | 74 | } 75 | 76 | static class Memory { 77 | 78 | List data = new ArrayList(); 79 | int capacity; 80 | 81 | public Memory(int capacity) { 82 | this.capacity = capacity; 83 | } 84 | 85 | void put (Object o) throws InterruptedException { 86 | synchronized (data) { 87 | while (data.size() == capacity) { 88 | data.wait(); 89 | } 90 | data.add(o); 91 | data.notifyAll(); 92 | } 93 | } 94 | 95 | Object get() throws InterruptedException { 96 | Object element = null; 97 | synchronized (data) { 98 | while (data.size() == 0) { 99 | data.wait(); 100 | } 101 | element = data.remove(data.size() - 1); 102 | data.notifyAll(); 103 | } 104 | return element; 105 | } 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /week10/2.Wednesday/README.md: -------------------------------------------------------------------------------- 1 | ### Implement a simple blocking queue. 2 | Implement a blocking queue with locks/conditions - just like a regular queue, with the difference that if someone calls `poll()` and the queue is empty, the call is blocked until somebody adds an element to the queue. After an element is added, the caller (the one who called `poll()`) gets unblocked and the `poll()` call returns. Create several threads (Producers) that only produce `add(E e)` in your queue and several threads (Consumers) that only consume `poll()` from your queue. Your blocking queue should have a max size. When a max size is reached all producers are halted until some object have been consumed. 3 | 4 | ### Parallel minimal point calculations 5 | 6 | Try to implement the following with some different approach and concurrent object from java.util.concurrent.*. 7 | Create a static method `generatePoints()` which returns a `List` - `create your Point impl (with maybe different implementations)` 8 | Implement it, generating a 100 000 points (in java that is written `100_000`) points with random coordinates - ranging from 0 to 10_000. 9 | 10 | Now, for each of those points, I'd like you to find it's nearest point. Do this in a method `Map getNearestPoints(List generatedPoints)` 11 | 12 | It takes a while. By calculations, it should take like lots of seconds to complete (depending on your CPU speed). 13 | 14 | Now introduce some multithreading to speed it up. 15 | Declare and implement a method `doCalculations(List inPoints, int indexFrom, int indexTo, Map outMap)`. 16 | Move calculations logic from `getNearestPoints` to `doCalculations`, but work strictly from `indexFrom`, to `indexTo`. 17 | 18 | Now in `getNearestPoints(List generatedPoints)` method, start two Threads that call `doCalculations`, in their run methods, one from 0 to half of the elements, the other from half of the elements to the last of them. 19 | 20 | Measure speedup between the two implementations (See `System.currentTimeMillis()`). 21 | 22 | Introduce a third and forth thread. Does your implementation go faster? 23 | 24 | Think how to generalize the number of threads and how to implement it. 25 | 26 | ### Reimplement atomic int with Lock objects - test and measure performance 27 | 28 | ### Implement advanced file search 29 | Implement search for a text in file contents. (Joker - think how to use producer-consumer pattern to speed that up) 30 | Your program, by given folder name, should find all the files inside it where a text is occurring and return the file name and in which line the match was found. 31 | 32 | ### Implement advanced concurrent data structure 33 | Implement a data structure over which several producers and consumers can work simultaneously, which means: 34 | - it is possible several producers to write into that structure simultaneously, 35 | - it is possible several consumer to read from that structure simultaneously, 36 | - it is possible several producers and consumers to read and write in that structure simultaneosly, 37 | Try to measure what's the speedup (from this structure over the not so concurrent one where only one reader or writer at a time is allowed to operate) to produce and consume an amount of items - N, with that structure. 38 | 39 | 40 | ### Measurement tool 41 | Implement a tool which has several confugurable factors: 42 | - number of producers 43 | - number of consumers 44 | - number of elements to be produced/consumed 45 | - size(number of elements) of a data structure to be used for shared memory 46 | Measure the time needed all elements to be consumed and let your program tell you what are the optimal configuration numbers. 47 | -------------------------------------------------------------------------------- /week10/2.Wednesday/prereading.md: -------------------------------------------------------------------------------- 1 | Important to read 2 | * https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html 3 | * https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html 4 | * http://tutorials.jenkov.com/java-concurrency/locks.html 5 | * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/StampedLock.html 6 | * https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html 7 | * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html 8 | * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html 9 | * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html 10 | * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Callable.html 11 | * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html 12 | * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html 13 | * https://www.securecoding.cert.org/confluence/display/java/THI03-J.+Always+invoke+wait()+and+await()+methods+inside+a+loop 14 | * https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html 15 | * https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html 16 | 17 | High Concurrency details and tricks 18 | * https://docs.oracle.com/javase/tutorial/essential/concurrency/highlevel.html 19 | 20 | *Books (that are considered for bibles)* 21 | - Java Concurrency in Practice by Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, and Doug Lea. 22 | - Concurrent Programming in Java: Design Principles and Pattern (2nd Edition) by Doug Lea, the architect of the Java platform's concurrency framework. 23 | 24 | *Lars Vogel's threading tutorial* 25 | http://www.vogella.com/tutorials/JavaConcurrency/article.html#forkjoin 26 | -------------------------------------------------------------------------------- /week10/3.Friday/README.md: -------------------------------------------------------------------------------- 1 | Try to implement the following with some different approach and concurrent objects from java.util.concurrent.*. 2 | 3 | ### Count odd numbers 4 | In 2 000 000 000 random numbers you should tell as fast as possible how many of them are odd and what's the 5 | configuration of your program so that it is so fast. 6 | 7 | ### Parallel minimal point calculations 8 | 9 | Create a static method `generatePoints()` which returns a `List` - `create your Point impl (with maybe different implementations)` 10 | Implement it, generating a 100 000 points (in java that is written `100_000`) points with random coordinates - ranging from 0 to 10_000. 11 | 12 | Now, for each of those points, I'd like you to find it's nearest point. Do this in a method `Map getNearestPoints(List generatedPoints)` 13 | 14 | It takes a while. By calculations, it should take like lots of seconds to complete (depending on your CPU speed). 15 | 16 | Now introduce some multithreading to speed it up. 17 | Declare and implement a method `doCalculations(List inPoints, int indexFrom, int indexTo, Map outMap)`. 18 | Move calculations logic from `getNearestPoints` to `doCalculations`, but work strictly from `indexFrom`, to `indexTo`. 19 | 20 | Now in `getNearestPoints(List generatedPoints)` method, start two Threads that call `doCalculations`, in their run methods, one from 0 to half of the elements, the other from half of the elements to the last of them. 21 | 22 | Measure speedup between the two implementations (See `System.currentTimeMillis()`). 23 | 24 | Introduce a third and forth thread. Does your implementation go faster? 25 | 26 | Think how to generalize the number of threads and how to implement it. 27 | 28 | ### Reimplement atomic int with Lock objects - test and measure performance 29 | 30 | ### Implement advanced file search 31 | Implement search for a text in file contents. (Joker - think how to use producer-consumer pattern to speed that up) 32 | Your program, by given folder name, should find all the files inside it where a text is occurring and return the file name and in which line the match was found. 33 | 34 | ### Implement advanced concurrent data structure 35 | Implement a data structure over which several producers and consumers can work simultaneously, which means: 36 | - it is possible several producers to write into that structure simultaneously, 37 | - it is possible several consumer to read from that structure simultaneously, 38 | - it is possible several producers and consumers to read and write in that structure simultaneosly, 39 | Try to measure what's the speedup (from this structure over the not so concurrent one where only one reader or writer at a time is allowed to operate) to produce and consume an amount of items - N, with that structure. 40 | 41 | 42 | ### Measurement tool 43 | Implement a tool which has several confugurable factors: 44 | - number of producers 45 | - number of consumers 46 | - number of elements to be produced/consumed 47 | - size(number of elements) of a data structure to be used for shared memory 48 | Measure the time needed all elements to be consumed and let your program tell you what are the optimal configuration numbers. 49 | -------------------------------------------------------------------------------- /week10/3.Friday/prereading.md: -------------------------------------------------------------------------------- 1 | Important to read 2 | * https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html 3 | * https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html 4 | * http://tutorials.jenkov.com/java-concurrency/locks.html 5 | * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/StampedLock.html 6 | * https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html 7 | * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html 8 | * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html 9 | * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html 10 | * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Callable.html 11 | * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Future.html 12 | * https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html 13 | * https://www.securecoding.cert.org/confluence/display/java/THI03-J.+Always+invoke+wait()+and+await()+methods+inside+a+loop 14 | * https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html 15 | * https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html 16 | 17 | High Concurrency details and tricks 18 | * https://docs.oracle.com/javase/tutorial/essential/concurrency/highlevel.html 19 | 20 | *Books (that are considered for bibles)* 21 | - Java Concurrency in Practice by Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, and Doug Lea. 22 | - Concurrent Programming in Java: Design Principles and Pattern (2nd Edition) by Doug Lea, the architect of the Java platform's concurrency framework. 23 | 24 | *Lars Vogel's threading tutorial* 25 | http://www.vogella.com/tutorials/JavaConcurrency/article.html#forkjoin 26 | -------------------------------------------------------------------------------- /week11/1.Monday/README.md: -------------------------------------------------------------------------------- 1 | ### 1. Download a file with java 2 | Using only URL and the stream classes, download this photo: http://d3dsacqprgcsqh.cloudfront.net/photo/aozrdx0_700b.jpg to a location of your choosing 3 | 4 | ##### Now accept files from the command line and label your program the 'java wget'. Woohoo! 5 | 6 | ### 2. Make a simple website crawler 7 | Have you grown tiiiiiiired of looking for stuff on websites that simply seems is not in the navigation menu at all? 8 | You grow tired of that... and suddenly, baaaam! Someone skypes you the link. It was there, how could I have not seen it. 9 | 10 | 11 | Today, we will put an end to that. 12 | 13 | Write a simple web crawler, that is receiving a URL as a command line parameter and a "needle" to search for. 14 | Needle is text, usually a sentence. 15 | 16 | What your crawler should do is simple 17 | - GET the contents of the URL received 18 | - Check if the contents contain "needle" 19 | - If they do, output the URL and exit 20 | - If they don't, **get all the links** from the URL given and repeat for every link. 21 | 22 | Hints/tips: 23 | - **Don't go out of the website's scope** - if a link in `abv.bg` points to google, well, don't follow google, please... 24 | - **Don't visit the same URL twice** 25 | - **Use regular expressions** for getting links. If you are unfamiliar with them, use the following method: 26 | ```java 27 | private static List getAllLinks(String content) { 28 | ArrayList resultList = new ArrayList<>(); 29 | String regex = ""; 30 | Pattern pattern = Pattern.compile(regex); 31 | Matcher matcher = pattern.matcher(content); 32 | while (matcher.find()) { 33 | resultList.add(matcher.group(1)); 34 | } 35 | return resultList; 36 | } 37 | ``` 38 | - **If you are not comfortable with even using something as ugly as regular expressions, you can do it with regular string matching. It will be harder though :(** 39 | - Use small websites for testing. For example, http://ebusiness.free.bg is one site you can use. It has very, very few links. (Search for the word 'Револвираща'.) 40 | 41 | ### 3. Create a weather forcasting tool 42 | First start with getting the weather in a concrete location using [OpenWeatherMap](http://openweathermap.org/current#name) REST service API. (You can use [Jettison library](http://jettison.codehaus.org/) and [Apache HttpClient](https://hc.apache.org/httpcomponents-client-ga/tutorial/html/)). 43 | 44 | Second thing is to think for a simple algorithm which can work for weather prediction. 45 | 46 | And the third thing (the most important one!!!) is how to design the entire tool (software design). 47 | -------------------------------------------------------------------------------- /week11/1.Monday/prereading.md: -------------------------------------------------------------------------------- 1 | URL vs URI 2 | * http://stackoverflow.com/questions/176264/whats-the-difference-between-a-uri-and-a-url 3 | * http://stackoverflow.com/questions/176264/what-is-the-difference-between-a-uri-a-url-and-a-urn/1984225#1984225 4 | * https://danielmiessler.com/study/url_vs_uri/ 5 | 6 | Reading directly from a URL 7 | * http://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html 8 | 9 | Apache HTTP Client 10 | * https://hc.apache.org/httpcomponents-client-ga/tutorial/html/ 11 | * http://stackoverflow.com/questions/7199969/apache-httpcore-simple-server-to-echo-received-post-data 12 | 13 | Apache HTTP Client Examples 14 | * https://hc.apache.org/httpcomponents-client-ga/examples.html 15 | 16 | REST 17 | * http://en.wikipedia.org/wiki/Representational_state_transfer 18 | * http://www.looah.com/source/view/2284 19 | 20 | let me google that for you: 21 | * json — http://stackoverflow.com/questions/383692/what-is-json-and-why-would-i-use-it 22 | 23 | 24 | Q&A 25 | * What is URL? 26 | * What is URI? 27 | * What is URN? 28 | * What is JSON? 29 | * What is JSON structure? Bonus: What is [Javascript Object](http://www.w3schools.com/tags/ref_httpmethods.asp)? 30 | * What is HTTP? 31 | * What is HTTP request? 32 | * What is POST, GET, DELETE request? 33 | * What is HTTP response? 34 | * What is HTTP header? 35 | * What is HTTP body? 36 | * What is HTTP query string? 37 | 38 | * SSL — http://info.ssl.com/article.aspx?id=10241 , http://en.wikipedia.org/wiki/Transport_Layer_Security 39 | * how to import library — http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-(Java) 40 | 41 | Bonus: 42 | * http://en.wikipedia.org/wiki/SOLID_(object-oriented_design) 43 | -------------------------------------------------------------------------------- /week11/2.Wednesday/README.md: -------------------------------------------------------------------------------- 1 | ### 0. Paralel web crawler 2 | There is a bottleneck in web crawling - while waiting for an answer from the server, the CPU does nothing. 3 | It would be better to make several requests at once. 4 | 5 | Try to crawl 9gag.com, for instance, and print every page you've visited. See the speed is not that great. 6 | Now Introduce parallelisation and speed up the solution. 7 | 8 | 9 | ### 1. Servlet/HelloWorld 10 | - Create an HttpServlet. Override the `doGet` method, and write 'HelloWorld!' to the response's outputStream. 11 | - Run your application on Eclipse ('Run as Server'). 12 | - See your own message at 'localhost:8080/YourAppName/YourServletName' 13 | - Make your servlet respond at 'localhost:8080/YourAppName/' (Edit the @WebServlet annotation path to '/') 14 | - See that your servlet now responds at 'localhost:8080/YourAppName/' 15 | - Now undo your change (restore the @WebServlet annotation path). 16 | - Right click on your project -> Java EE tools -> Generate Deployment descriptor stub. 17 | - - You will now have a 'web.xml' file. It is called a deployment descriptor. 18 | - - Edit the deployment descriptor, and add a first welcome-file tag pointing to 'YourServletName'. We want to register the servlet as a welcome page for your server :) 19 | - Check the 'html source code' returned by your servlet. You will see no HTML tags. Why? 20 | - Write an HTML response to your client. For instance `

Now that's a big title!

` 21 | 22 | Congratulations. You've just witnessed what ASP/JSP/PHP is all about. We are not going to do any of that ~~sh**~~ stuff. 23 | 24 | 25 | ### 2. Simple news agregator 26 | Do you know what an [RSS](http://en.wikipedia.org/wiki/RSS) is? 27 | It is a simple format for describing **content** (just the content, and not it's visualization). It is an XML-based format. 28 | 29 | [This is an RSS](http://www.sportal.bg/uploads/rss_category_2.xml) 30 | Your task is simple - create a service (using just a servlet), that shows the latest news **in bulgarian** in the following categories: 31 | - General/Bulgaria 32 | - Technology 33 | - Sport 34 | 35 | Write the ~~ugliest~~ simplest html output you possibly can. 36 | Something like is completely OK. 37 | ![this](http://i.imgur.com/uZvmOlRl.jpg) 38 | 39 | 40 | If you don't know HTML, it's okay, just check http://www.w3schools.com/html/html_basic.asp You'll learn a few tricks in no time. 41 | 42 | Hints: 43 | - Pick some RSS feed links from popular news websites. Dnevnik.bg, sportal.bg, etc have RSS feed functionality. Maybe even FMI had one? 44 | - Do not parse the XML yourself. There are libraries for that, use the ones given in this github folder (the ROME library). 45 | - Add both jars in the WEB-INF/lib folder. Don't do anything after that, Eclipse will automatically add them to the project's build path. 46 | - Use this ROME tutorial: http://blog.manishchhabra.com/2011/10/rome-library-example-for-parsing-rss-and-atom-feeds/ 47 | 48 | 49 | ### 3. Simple JSON pretty printer service. 50 | Just look at the JSON at [London weather](http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98). It is horrible - completely unreadable. What are the elements? What are the JSON objects? You cannot easily tell. 51 | 52 | - Deploy a servlet, that accepts a named "POST" parameter "json". 53 | - Read the json as a POST parameter given to the request (as a parameter from the `HttpServletRequest` via the `getParameter` method.) 54 | - Use google gson to pretty-print the json given. 55 | - See how to it here: http://stackoverflow.com/questions/4105795/pretty-print-json-in-java 56 | -------------------------------------------------------------------------------- /week11/2.Wednesday/prereading.md: -------------------------------------------------------------------------------- 1 | *In short, what is a servlet?* 2 | http://stackoverflow.com/questions/7213541/what-is-java-servlet 3 | 4 | *This is how you create your first servlet* 5 | http://www.journaldev.com/1854/java-web-application-tutorial-for-beginners 6 | 7 | *If you want to learn more about servlets here is a short book (or an extended tutorial)* 8 | http://pdf.coreservlets.com/Servlet-Basics.pdf 9 | 10 | *And of course, Oracle's documentation on servlets __#tl;dr__* 11 | http://docs.oracle.com/javaee/6/tutorial/doc/bnafe.html 12 | 13 | *Eclipse EE* 14 | https://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/lunar 15 | 16 | *TomEE JAX-RS* 17 | http://www.apache.org/dyn/closer.cgi/tomee/tomee-1.7.1/apache-tomee-1.7.1-jaxrs.zip 18 | 19 | ### Stop the Tomcat instance launched from Eclipse 20 | Shutdown Eclipse's use of tomcat. We will not let Eclipse manage tomcat for us this time. 21 | Forget Run as -> Server. We won't be using that again. 22 | 23 | If you do not have running Tomcat instance from Eclipse, you don't have to do anything. 24 | Else, just click on the red button in the'Servers' view. 25 | 26 | (If you've just launched Eclipse, you don't have to do anything) 27 | 28 | ### Check out tomcat's installation directory 29 | -Go to your tomcat installation directory. For me, it was `/home/georgi/Dev/tomcat/` 30 | -Do an `ls` and notify me when you get there. 31 | 32 | - `tomcat/bin` => All the binaries for tomcat. If you need to start or stop tomcat, there are the binaries you need. 33 | - `tomcat/conf` => All the configuration files for tomcat. tomcat-user.xml and others 34 | - `tomcat/webapps` => The most important folder of all. You must delpoy your web applications here. 'Deploying' means copying one .war file to your webapps dir. 35 | 36 | One web application = one .war file. It's like a .jar file, but it means 'webarchive' (.war). 37 | 38 | -Start your tomcat using `startup.sh` or `startup.bat` in the `/bin/` folder. 39 | 40 | -Go to http://localhost:8080 . Do you see the cat? You need to see the cat. 41 | -Now take a look at http://localhost:8080/examples/ 42 | 43 | -Take a note - if you let eclipse manage your tomcat, you won't see neither a cat nor examples. 44 | 45 | -Edit the tomcat-users.xml file in `your-tomcat-dir/conf`. See the commented lines and add *2 roles* one with a `rolеname="manager"` and the other with a `rolеname="manager-gui"`. 46 | -Create a user with username "a" and password "a" with the role of "manager-gui" 47 | -Create a user with username "test" and password "test" with the role of "manager" 48 | -Save tomcat-users.xml 49 | 50 | -Open http://localhost:8080/manager . Authenticate with "a"/"a". 51 | -What you are seeing now is something called the "Tomcat Manager". Here you can see what applications do you have deployed, which of them are running, etc. If you have any problems with web applications, that's the place to check first: 52 | -1) Your web application should be DEPLOYED 53 | -2) Your web application should be RUNNING 54 | 55 | ### In Eclipse 56 | - Create your Dynamic Web project. Name your project 'NewsService'. 57 | - Create a servlet echoing "Hello World!" to the writer in the `doGet` method 58 | - Add apache's commons-io library. 59 | 60 | -------------------------------------------------------------------------------- /week11/3.Friday/Axway_JAAS_HackBulgaria_2016.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/week11/3.Friday/Axway_JAAS_HackBulgaria_2016.pptx -------------------------------------------------------------------------------- /week11/3.Friday/HackBulgariaJAASReferenceProject/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | HackBulgariaJAASReferenceProject 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /week11/3.Friday/HackBulgariaJAASReferenceProject/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=1.7 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.source=1.7 12 | -------------------------------------------------------------------------------- /week11/3.Friday/HackBulgariaJAASReferenceProject/bin/com/axway/cdg/jaas/reference/project/framework/RefJAASCallbackHandler.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/week11/3.Friday/HackBulgariaJAASReferenceProject/bin/com/axway/cdg/jaas/reference/project/framework/RefJAASCallbackHandler.class -------------------------------------------------------------------------------- /week11/3.Friday/HackBulgariaJAASReferenceProject/bin/com/axway/cdg/jaas/reference/project/framework/UserPrincipal.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/week11/3.Friday/HackBulgariaJAASReferenceProject/bin/com/axway/cdg/jaas/reference/project/framework/UserPrincipal.class -------------------------------------------------------------------------------- /week11/3.Friday/HackBulgariaJAASReferenceProject/bin/com/axway/cdg/jaas/reference/project/main/MyFirstJAASApplication.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/week11/3.Friday/HackBulgariaJAASReferenceProject/bin/com/axway/cdg/jaas/reference/project/main/MyFirstJAASApplication.class -------------------------------------------------------------------------------- /week11/3.Friday/HackBulgariaJAASReferenceProject/bin/com/axway/cdg/jaas/reference/project/modules/StandardLoginModule.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/week11/3.Friday/HackBulgariaJAASReferenceProject/bin/com/axway/cdg/jaas/reference/project/modules/StandardLoginModule.class -------------------------------------------------------------------------------- /week11/3.Friday/HackBulgariaJAASReferenceProject/bin/com/axway/cdg/jaas/reference/project/modules/UsernameLoginModule.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/week11/3.Friday/HackBulgariaJAASReferenceProject/bin/com/axway/cdg/jaas/reference/project/modules/UsernameLoginModule.class -------------------------------------------------------------------------------- /week11/3.Friday/HackBulgariaJAASReferenceProject/jaas.config: -------------------------------------------------------------------------------- 1 | RefJAASConfiguration { 2 | com.axway.cdg.jaas.reference.project.modules.StandardLoginModule sufficient debug=true; 3 | com.axway.cdg.jaas.reference.project.modules.UsernameLoginModule sufficient debug=true; 4 | }; -------------------------------------------------------------------------------- /week11/3.Friday/HackBulgariaJAASReferenceProject/src/com/axway/cdg/jaas/reference/project/framework/RefJAASCallbackHandler.java: -------------------------------------------------------------------------------- 1 | package com.axway.cdg.jaas.reference.project.framework; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.security.auth.callback.Callback; 6 | import javax.security.auth.callback.CallbackHandler; 7 | import javax.security.auth.callback.NameCallback; 8 | import javax.security.auth.callback.PasswordCallback; 9 | import javax.security.auth.callback.UnsupportedCallbackException; 10 | 11 | /** 12 | * A callback handler definition. 13 | * The purpose of this callback handler is to run a function 14 | * that will make certain variables available for login modules. 15 | * 16 | * @author aandreev 17 | * 18 | */ 19 | public class RefJAASCallbackHandler implements CallbackHandler { 20 | 21 | /** 22 | * Username. 23 | */ 24 | private String name; 25 | 26 | /** 27 | * Password. 28 | */ 29 | private String password; 30 | 31 | /** 32 | * A constructor. 33 | * 34 | * @param name - login name of the user 35 | * @param password - password of the user 36 | */ 37 | public RefJAASCallbackHandler(String name, String password) { 38 | this.name = name; 39 | this.password = password; 40 | } 41 | 42 | @Override 43 | public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { 44 | for (int i = 0; i < callbacks.length; i++) { 45 | Callback callback = callbacks[i]; 46 | if (callback instanceof NameCallback) { 47 | NameCallback nc = (NameCallback) callback; 48 | nc.setName(name); 49 | } else if (callback instanceof PasswordCallback) { 50 | PasswordCallback pc = (PasswordCallback) callback; 51 | pc.setPassword(password.toCharArray()); 52 | } 53 | } 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /week11/3.Friday/HackBulgariaJAASReferenceProject/src/com/axway/cdg/jaas/reference/project/framework/UserPrincipal.java: -------------------------------------------------------------------------------- 1 | package com.axway.cdg.jaas.reference.project.framework; 2 | 3 | import java.security.Principal; 4 | 5 | /** 6 | * A Principal to contain the name characteristics of the user. 7 | * 8 | * Principal as a characteristics, should become part of a subject. 9 | * The subject may be considered as the authenticated identity of the user, 10 | * that may contain multiple characteristics - principals. 11 | * 12 | * @author aandreev 13 | * 14 | */ 15 | public class UserPrincipal implements Principal { 16 | 17 | /** 18 | * Username characteristics. 19 | */ 20 | private String name; 21 | 22 | /** 23 | * Constructor. 24 | * 25 | * @param username - name of the user 26 | */ 27 | public UserPrincipal(String username) { 28 | this.name = username; 29 | } 30 | 31 | @Override 32 | public String getName() { 33 | return name; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /week11/3.Friday/HackBulgariaJAASReferenceProject/src/com/axway/cdg/jaas/reference/project/main/MyFirstJAASApplication.java: -------------------------------------------------------------------------------- 1 | package com.axway.cdg.jaas.reference.project.main; 2 | 3 | import java.security.Principal; 4 | import java.util.Scanner; 5 | import java.util.Set; 6 | 7 | import javax.security.auth.login.LoginContext; 8 | import javax.security.auth.login.LoginException; 9 | 10 | import com.axway.cdg.jaas.reference.project.framework.RefJAASCallbackHandler; 11 | 12 | /** 13 | * Main program of our application. 14 | * The application uses JAAS for authentication mechanism. 15 | * 16 | * @author aandreev 17 | * 18 | */ 19 | public class MyFirstJAASApplication { 20 | 21 | /** 22 | * @param args 23 | */ 24 | public static void main(String[] args) { 25 | 26 | System.out.println("Hello My first JAAS application"); 27 | Scanner scan = new Scanner(System.in); 28 | 29 | System.out.println("Enter username:"); 30 | String username = scan.next(); 31 | 32 | 33 | System.out.println("Enter password:"); 34 | String password = scan.next(); 35 | 36 | //Set JAAS configuration file - it basically contains a list of login modules only 37 | System.setProperty("java.security.auth.login.config", "jaas.config"); 38 | 39 | // create a callback handler that will process data between the JAAS framework and login modules 40 | // this is basically an additional object used to store user data, from which login modules read data, 41 | // instead of directly doing it through the application 42 | RefJAASCallbackHandler callbackHandler = new RefJAASCallbackHandler(username, password); 43 | 44 | // JAAS starts here - the LoginContext is actually the JAAS login component in which authentication occurrs 45 | LoginContext lc = null; 46 | try { 47 | lc = new LoginContext("RefJAASConfiguration", callbackHandler); 48 | lc.login(); 49 | // JAAS ends here - if we get to here, this means that JAAS authentication completed successfully 50 | // Let`s check who the logged in user is by revising the principals 51 | // in our case we expect only one Principal 52 | Set principals = lc.getSubject().getPrincipals(); 53 | for (Principal principal : principals) { 54 | System.out.println("User [" + principal.getName() + "] authenticated successfully."); 55 | } 56 | } catch (LoginException e) { 57 | // if we get to here - this means that JAAS authentication failed. 58 | System.out.println("User [" + username + "] did not authenticate successfully with password [" + password + "]"); 59 | e.printStackTrace(); 60 | } 61 | 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /week11/3.Friday/HackBulgariaJAASReferenceProject/src/com/axway/cdg/jaas/reference/project/modules/UsernameLoginModule.java: -------------------------------------------------------------------------------- 1 | package com.axway.cdg.jaas.reference.project.modules; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.IOException; 6 | import java.util.Map; 7 | import java.util.Properties; 8 | 9 | import javax.security.auth.Subject; 10 | import javax.security.auth.callback.Callback; 11 | import javax.security.auth.callback.CallbackHandler; 12 | import javax.security.auth.callback.NameCallback; 13 | import javax.security.auth.callback.UnsupportedCallbackException; 14 | import javax.security.auth.login.LoginException; 15 | import javax.security.auth.spi.LoginModule; 16 | 17 | /** 18 | * A login module that only verifies the user name. 19 | * 20 | * @author aandreev 21 | * 22 | */ 23 | public class UsernameLoginModule implements LoginModule { 24 | 25 | private Subject subject; 26 | 27 | private CallbackHandler callbackhandler; 28 | 29 | @Override 30 | public boolean abort() throws LoginException { 31 | // TODO Auto-generated method stub 32 | return true; 33 | } 34 | 35 | @Override 36 | public boolean commit() throws LoginException { 37 | // TODO Auto-generated method stub 38 | return true; 39 | } 40 | 41 | @Override 42 | public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) { 43 | this.subject = subject; 44 | this.callbackhandler = callbackHandler; 45 | 46 | } 47 | 48 | @Override 49 | public boolean login() throws LoginException { 50 | NameCallback usernameCallback = new NameCallback("Username"); 51 | try { 52 | callbackhandler.handle(new Callback[] {usernameCallback}); 53 | String username = usernameCallback.getName(); 54 | 55 | Properties props = new Properties(); 56 | props.load(new FileInputStream(new File("users.properties"))); 57 | if (props.containsKey(username)) { 58 | System.out.println("Username Login Module succeeded."); 59 | return true; 60 | } 61 | } catch (IOException e) { 62 | // TODO Auto-generated catch block 63 | e.printStackTrace(); 64 | } catch (UnsupportedCallbackException e) { 65 | // TODO Auto-generated catch block 66 | e.printStackTrace(); 67 | } 68 | return false; 69 | } 70 | 71 | @Override 72 | public boolean logout() throws LoginException { 73 | // TODO Auto-generated method stub 74 | return false; 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /week11/3.Friday/HackBulgariaJAASReferenceProject/users.properties: -------------------------------------------------------------------------------- 1 | aandreev=123 -------------------------------------------------------------------------------- /week11/3.Friday/README.md: -------------------------------------------------------------------------------- 1 | ### Axway + JAAS 2 | -------------------------------------------------------------------------------- /week12/1.Monday/README.md: -------------------------------------------------------------------------------- 1 | ### 1. Servlet/HelloWorld 2 | - Create an HttpServlet. Override the `doGet` method, and write 'HelloWorld!' to the response's outputStream. 3 | - Run your application on Eclipse ('Run as Server'). 4 | - See your own message at 'localhost:8080/YourAppName/YourServletName' 5 | - Make your servlet respond at 'localhost:8080/YourAppName/' (Edit the @WebServlet annotation path to '/') 6 | - See that your servlet now responds at 'localhost:8080/YourAppName/' 7 | - Now undo your change (restore the @WebServlet annotation path). 8 | - Right click on your project -> Java EE tools -> Generate Deployment descriptor stub. 9 | - - You will now have a 'web.xml' file. It is called a deployment descriptor. 10 | - - Edit the deployment descriptor, and add a first welcome-file tag pointing to 'YourServletName'. We want to register the servlet as a welcome page for your server :) 11 | - Check the 'html source code' returned by your servlet. You will see no HTML tags. Why? 12 | - Write an HTML response to your client. For instance `

Now that's a big title!

` 13 | 14 | Congratulations. You've just witnessed what ASP/JSP/PHP is all about. We are not going to do any of that ~~sh**~~ stuff. 15 | 16 | 17 | ### 2. Simple news agregator 18 | Do you know what an [RSS](http://en.wikipedia.org/wiki/RSS) is? 19 | It is a simple format for describing **content** (just the content, and not it's visualization). It is an XML-based format. 20 | 21 | [This is an RSS](http://www.sportal.bg/uploads/rss_category_2.xml) 22 | Your task is simple - create a service (using just a servlet), that shows the latest news **in bulgarian** in the following categories: 23 | - General/Bulgaria 24 | - Technology 25 | - Sport 26 | 27 | Write the ~~ugliest~~ simplest html output you possibly can. 28 | Something like is completely OK. 29 | ![this](http://i.imgur.com/uZvmOlRl.jpg) 30 | 31 | 32 | If you don't know HTML, it's okay, just check http://www.w3schools.com/html/html_basic.asp You'll learn a few tricks in no time. 33 | 34 | Hints: 35 | - Pick some RSS feed links from popular news websites. Dnevnik.bg, sportal.bg, etc have RSS feed functionality. Maybe even FMI had one? 36 | - Do not parse the XML yourself. There are libraries for that, use the ones given in this github folder (the ROME library). 37 | - Add both jars in the WEB-INF/lib folder. Don't do anything after that, Eclipse will automatically add them to the project's build path. 38 | - Use this ROME tutorial: http://blog.manishchhabra.com/2011/10/rome-library-example-for-parsing-rss-and-atom-feeds/ 39 | 40 | 41 | ### 3. Simple JSON pretty printer service. 42 | Just look at the JSON at [London weather](http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98). It is horrible - completely unreadable. What are the elements? What are the JSON objects? You cannot easily tell. 43 | 44 | - Deploy a servlet, that accepts a named "POST" parameter "json". 45 | - Read the json as a POST parameter given to the request (as a parameter from the `HttpServletRequest` via the `getParameter` method.) 46 | - Use google gson to pretty-print the json given. 47 | - See how to it here: http://stackoverflow.com/questions/4105795/pretty-print-json-in-java 48 | -------------------------------------------------------------------------------- /week12/1.Monday/jdom-1.1.3.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/week12/1.Monday/jdom-1.1.3.zip -------------------------------------------------------------------------------- /week12/1.Monday/prereading.md: -------------------------------------------------------------------------------- 1 | *In short, what is a servlet?* 2 | http://stackoverflow.com/questions/7213541/what-is-java-servlet 3 | 4 | *This is how you create your first servlet* 5 | http://www.journaldev.com/1854/java-web-application-tutorial-for-beginners 6 | 7 | *If you want to learn more about servlets here is a short book (or an extended tutorial)* 8 | http://pdf.coreservlets.com/Servlet-Basics.pdf 9 | 10 | *And of course, Oracle's documentation on servlets* 11 | http://docs.oracle.com/javaee/6/tutorial/doc/bnafe.html 12 | 13 | *Eclipse EE* 14 | https://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/lunar 15 | 16 | *TomEE JAX-RS* 17 | http://www.apache.org/dyn/closer.cgi/tomee/tomee-1.7.1/apache-tomee-1.7.1-jaxrs.zip 18 | 19 | ### Stop the Tomcat instance launched from Eclipse 20 | Shutdown Eclipse's use of tomcat. We will not let Eclipse manage tomcat for us this time. 21 | Forget Run as -> Server. We won't be using that again. 22 | 23 | If you do not have running Tomcat instance from Eclipse, you don't have to do anything. 24 | Else, just click on the red button in the'Servers' view. 25 | 26 | (If you've just launched Eclipse, you don't have to do anything) 27 | 28 | ### Check out tomcat's installation directory 29 | -Go to your tomcat installation directory. For me, it was `/home/georgi/Dev/tomcat/` 30 | -Do an `ls` and notify me when you get there. 31 | 32 | - `tomcat/bin` => All the binaries for tomcat. If you need to start or stop tomcat, there are the binaries you need. 33 | - `tomcat/conf` => All the configuration files for tomcat. tomcat-user.xml and others 34 | - `tomcat/webapps` => The most important folder of all. You must delpoy your web applications here. 'Deploying' means copying one .war file to your webapps dir. 35 | 36 | One web application = one .war file. It's like a .jar file, but it means 'webarchive' (.war). 37 | 38 | -Start your tomcat using `startup.sh` or `startup.bat` in the `/bin/` folder. 39 | 40 | -Go to http://localhost:8080 . Do you see the cat? You need to see the cat. 41 | -Now take a look at http://localhost:8080/examples/ 42 | 43 | -Take a note - if you let eclipse manage your tomcat, you won't see neither a cat nor examples. 44 | 45 | -Edit the tomcat-users.xml file in `your-tomcat-dir/conf`. See the commented lines and add *2 roles* one with a `rolеname="manager"` and the other with a `rolеname="manager-gui"`. 46 | -Create a user with username "a" and password "a" with the role of "manager-gui" 47 | -Create a user with username "test" and password "test" with the role of "manager" 48 | -Save tomcat-users.xml 49 | 50 | -Open http://localhost:8080/manager . Authenticate with "a"/"a". 51 | -What you are seeing now is something called the "Tomcat Manager". Here you can see what applications do you have deployed, which of them are running, etc. If you have any problems with web applications, that's the place to check first: 52 | -1) Your web application should be DEPLOYED 53 | -2) Your web application should be RUNNING 54 | 55 | ### In Eclipse 56 | - Create your Dynamic Web project. Name your project 'NewsService'. 57 | - Create a servlet echoing "Hello World!" to the writer in the `doGet` method 58 | - Add apache's commons-io library. 59 | 60 | -------------------------------------------------------------------------------- /week12/1.Monday/rome-1.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HackBulgaria/Programming101-Java/e46ba2bd486a502772b4a43b5cb5b027b6c6efc5/week12/1.Monday/rome-1.0.jar -------------------------------------------------------------------------------- /week12/2.Wednesday/README.md: -------------------------------------------------------------------------------- 1 | # Introduction to SQL 2 | 3 | ## Data Definition Language 4 | 5 | We will create a database for Our Company to store information about our employees, products and customers. For that purpose create a new database `OurCompany`. Create the appropriate tables and relationships between them. Don't forget to create a column and a primary key for each table! 6 | 7 | It is a good idea to save the `.sql` scripts and save them in your repository. 8 | 9 | ### Departments and employees 10 | 11 | The company has several departments a hierarchy of employees: 12 | * Each department has: 13 | * Name 14 | * Each employee has: 15 | * Name 16 | * Email - optional 17 | * Date of birth 18 | * Manager - another employee that is his/her manager. The big boss doesn't have a manager. 19 | * Department - the department the employee works in. The big boss doesn't have a department. 20 | 21 | ### Products 22 | The company creates products with different categories: 23 | * Each category has: 24 | * Unique 3 letter code 25 | * Name 26 | * Each product has: 27 | * Name 28 | * Single price 29 | * Category 30 | 31 | ### Customers 32 | The company keeps track of its customers: 33 | * Each customer has: 34 | * Name 35 | * Email - optional 36 | * Address 37 | * Discount - a percent discount applied to everything the customer buys; optional 38 | 39 | ### Orders 40 | The company keeps track of all orders: 41 | Each order has: 42 | * Date and time of the order 43 | * Customer 44 | * Total Price 45 | * Each order may contain several products with different quantities - implement it as a many-to-many relationship with an additional table OrderProducts. 46 | 47 | ## Populating the database 48 | 49 | ### Departments and employees 50 | 51 | Into the database insert 3 departments - Sales, Production, Financial. 52 | 53 | Insert an entry for the Big Boss (has no manager and department). 54 | 55 | Insert 5 employees into each of the departments. In each department there is a manager: 56 | * He is the manager of all other employees in the department 57 | * His manager is the Big Boss 58 | 59 | ### Products 60 | 61 | Insert 4 product categories - Books, Music, Hardware, Software 62 | 63 | Inside each category insert at least 3 products 64 | 65 | ### Customers 66 | 67 | Insert at least 5 different customers with at least 2 having a discount. 68 | 69 | ### Orders 70 | 71 | Insert at least 5 orders with each having at least 2 products. 72 | 73 | ## Selecting from and manipulating the database 74 | 75 | ### Selecting 76 | 77 | * Select the big boss 78 | * Select all department managers 79 | * Select all employees in the Sales department ordered by Name 80 | * Select all departments with employees that are born after 1990 81 | * Select all departments with more than 3 employees 82 | * Select the department having the most employees 83 | * Select the order having the maximum total number of products 84 | * Select the average discount of all customers 85 | 86 | ### Manipulating 87 | * Update all employees adding 1 year to their birth date 88 | * Double the discount of the customer with most orders 89 | * Delete all products with no orders 90 | 91 | ### How to: 92 | * Return the number of times a specific product is ordered(by productId) 93 | * Switch the Big Boss with regular employee 94 | 95 | -------------------------------------------------------------------------------- /week12/2.Wednesday/prereading.md: -------------------------------------------------------------------------------- 1 | * http://www.tutorialspoint.com/jdbc/ 2 | * https://docs.oracle.com/javase/tutorial/jdbc/basics/ 3 | * http://www.w3schools.com/SQL/ 4 | * http://javarevisited.blogspot.bg/2012/08/top-10-jdbc-best-practices-for-java.html 5 | * http://www.mkyong.com/tutorials/jdbc-tutorials/ 6 | * http://sqlfiddle.com 7 | 8 | * http://www.postgresql.org 9 | * https://jdbc.postgresql.org 10 | * http://stackoverflow.com/questions/10861260/how-to-create-user-for-a-db-in-postgresql 11 | * http://www.pgadmin.org 12 | * http://www.mkfoster.com/2008/12/21/setting-up-postgresql-on-linux-and-connecting-using-pgadmin-iii/ 13 | -------------------------------------------------------------------------------- /week12/3.Friday/README.md: -------------------------------------------------------------------------------- 1 | ### Help our educational system 2 | 3 | Design and implement a database of tests which have questions with answers. Your app should generate you a test which chooses 10 4 | questions, for each question chooses 3 wrong and 1 correct answer and leave you to fill it. After you complete it - it tells you 5 | the result you have and saves it in scoreboard. Fill your DB with at least 15 questions which has more than 4 wrong and 2 correct 6 | answers. You program can be a command line tool taking your input, generate you test, giving you ability to fill it, then tells 7 | your result, saves it in the DB and you can see a scoreboard. 8 | -------------------------------------------------------------------------------- /week12/3.Friday/prereading.md: -------------------------------------------------------------------------------- 1 | * http://www.tutorialspoint.com/jdbc/ 2 | * https://docs.oracle.com/javase/tutorial/jdbc/basics/ 3 | * http://www.w3schools.com/SQL/ 4 | * http://javarevisited.blogspot.bg/2012/08/top-10-jdbc-best-practices-for-java.html 5 | * http://www.mkyong.com/tutorials/jdbc-tutorials/ 6 | * http://sqlfiddle.com 7 | 8 | * http://www.postgresql.org 9 | * https://jdbc.postgresql.org 10 | * http://stackoverflow.com/questions/10861260/how-to-create-user-for-a-db-in-postgresql 11 | * http://www.pgadmin.org 12 | * http://www.mkfoster.com/2008/12/21/setting-up-postgresql-on-linux-and-connecting-using-pgadmin-iii/ 13 | -------------------------------------------------------------------------------- /week13/1.Monday/README.md: -------------------------------------------------------------------------------- 1 | # Drone Delivery System 2 | 3 | Recently the geeks at Amazon turn up with the cool idea to use drones to deliver goods right in front of your front door. Nice idea! However it may be not so simple to implement. 4 | 5 | We are going to design and implement a system controlling and scheduling deliveries with drones. 6 | 7 | ## Our city 8 | 9 | For the sake of simplicity our city will be a 1000x1000 square matrix. Our drones will fly around it and deliver the goods. 10 | 11 | ## Drones 12 | 13 | * Each drone has a: 14 | * unique id - we should have a way to distinguish them 15 | * battery - unfortunately they cannot run forever but will usually last a flight to the end of the city and back, then they must recharge. We will measure them with BU (battery units). 16 | * capacity - they cannot take infinitely many products as well. We will measure their capacity with WU (weight units) 17 | * charging rate - measured in BU per minutes 18 | 19 | ## Products 20 | 21 | * Each product has a: 22 | * name (e.g. keyboard) 23 | * weight per quanitity (0.5 kg for 1 keyboard) 24 | 25 | ## Warehouse 26 | 27 | At the warehouse we will store the goods that should be delivered. 28 | 29 | * Each warehouse has a: 30 | * coordinates - the place in our city 31 | * information about the available products - we should keep track of the quiantities we have of a given product. 32 | 33 | ## Requests 34 | 35 | Lets suppose that we will receive the requests from console as a simple text. 36 | 37 | We will support the following requests: 38 | 39 | ### Delivery request 40 | 41 | It will look like this: 42 | 43 | delivery <id> <timestamp> <target coordinates> <product name 1> <quantity> <product name 2> <quantity> ... 44 | 45 | e.g. "delivery 4 2016-10-25 12:31 420,369 keyboard 5 tomatoes 20" 46 | 47 | ### Supply request 48 | 49 | It will look like this: 50 | 51 | supply <id> <timestamp YYYY-MM-DD HH:MM> <product name 1> <product weight> <quantity> <product name 2> <product weight> <quantity> 52 | 53 | e.g. "supply 5 2016-10-25 12:32 tomato 5 100 potatoes 6 50 cheese 2 4" 54 | 55 | ## How deliveries are made 56 | 57 | * When we receive a supply request we will simply update our information at the warehouse and log a message about the supply. 58 | 59 | * When we receive a delivery request we will try to execute it. If we can execute the delivery request we should log a message containing the ETA (estimated time of arrival). If we cannot process the current request now we should log a message with the reason why we cannot process the task. 60 | 61 | 62 | ### Executing 63 | 64 | If we have the needed amount of each product for a given delivery task we should be able to process it. If the WU (weight capacity) of one drone is not enough for processing the delivery we should use as much drones as we need. 65 | 66 | If we do not have the needed amount of at least one product we should log an error message. 67 | Bonus points if we execute it later (after a supply) 68 | 69 | ### Estimating ETA 70 | 71 | Each drone needs a minute for each DU (distance unit) travelled and will use 1 BU (battery unit) for each DU. 72 | 73 | The DUs are calculated as follows: The distance from cell [x1, y1] to cell [x2, y2] is calculated as ((x1 - x2)^2 + (y1 - y2)^2)^-2 (two-dimensional Euclidean distance). 74 | 75 | Moreover the drone needs a minute for each different product to load and a minute for each different product to unload at the target location. No BUs are used during loading/unloading. 76 | 77 | The batteries of the drones can be charged only at the warehouse. 78 | Take this in consideration when calculating the ETA. 79 | 80 | The ETA is the time that the last drone has unloaded the goods at the location. 81 | 82 | ## Drone Delivery System v1 83 | 84 | For our first version of the delivery system: 85 | 86 | * Our 50 drones will have: 87 | * 2 000 BU 88 | * 5 BU/min charging rate 89 | * 500 WU capacity 90 | 91 | * The warehouse is at coordinates [42, 42] 92 | 93 | ## Drone Delivery System v2 94 | 95 | Thanks to the great first version of the Delivery System, our delivery business has expnaded ! Now more companies are using our drones for their delivery requests. 96 | 97 | In fact so much that we have to proccess many requests simultaneously (yup, this means concurrently). We will receive this requests as multiple files. 98 | 99 | In order to keep up with the new loads we have bought 30 more drones: 100 | 101 | * Our new Chinese drones have: 102 | * 1 200 BU 103 | * 3 BU/min charging rate 104 | * 200 WU capacity -------------------------------------------------------------------------------- /week13/1.Monday/teams.md: -------------------------------------------------------------------------------- 1 | Katia 2 | Vasko 3 | Stef4o 4 | 5 | Veronika 6 | PlamenM 7 | Svetlio 8 | 9 | Angel 10 | PlamenNЪ 11 | Adasha 12 | 13 | Borislav 14 | Ivan 15 | Krasimir 16 | 17 | Hristo 18 | GeorgiA 19 | Tonka 20 | 21 | George 22 | Nikola 23 | IvanP 24 | 25 | Mariana 26 | Anjelo 27 | Nikolai 28 | 29 | Martin 30 | Cvetan 31 | Vasil 32 | 33 | -------------------------------------------------------------------------------- /week14/1.Monday/README.md: -------------------------------------------------------------------------------- 1 | # Tasks 2 | 3 | Your task is to go look at previous tasks, their implementation and choose the applicable who can be improved with using Dependency Injection. 4 | -------------------------------------------------------------------------------- /week14/1.Monday/prereading.md: -------------------------------------------------------------------------------- 1 | * http://www.journaldev.com/2461/spring-ioc-container-and-spring-bean-example-tutorial 2 | * https://dzone.com/articles/dependency-injection-an-introd 3 | * http://javapapers.com/spring/dependency-injection-di-with-spring/ 4 | * http://www.springbyexample.org/examples/part-intro.html 5 | -------------------------------------------------------------------------------- /week14/3.Friday/Java8Problems/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Java8Problems 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.m2e.core.maven2Nature 21 | org.eclipse.jdt.core.javanature 22 | 23 | 24 | -------------------------------------------------------------------------------- /week14/3.Friday/Java8Problems/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=1.8 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 12 | org.eclipse.jdt.core.compiler.source=1.8 13 | -------------------------------------------------------------------------------- /week14/3.Friday/Java8Problems/.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /week14/3.Friday/Java8Problems/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | Java8Problems 4 | Java8Problems 5 | 0.0.1-SNAPSHOT 6 | 7 | src 8 | test 9 | 10 | 11 | maven-compiler-plugin 12 | 3.1 13 | 14 | 1.8 15 | 1.8 16 | 17 | 18 | 19 | 20 | 21 | 22 | org.reflections 23 | reflections 24 | 0.9.9 25 | 26 | 27 | -------------------------------------------------------------------------------- /week14/3.Friday/Java8Problems/src/com/hackbulgaria/corejava101/StudentOperations.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava101; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import com.hackbulgaria.corejava101.data.Gender; 7 | import com.hackbulgaria.corejava101.data.Student; 8 | 9 | public interface StudentOperations { 10 | 11 | public double getAverageMark(); 12 | 13 | public List getAllPassing(); 14 | 15 | public List getAllFailing(); 16 | 17 | /** 18 | * Split the list of students into two groups - a group with equal or higher marks than the given `splitMark` ('true') 19 | * and the one with lower marks than the given `splitMark` ('false') 20 | * @return 21 | */ 22 | public Map> splitStudentsByMarks(float splitMark); 23 | 24 | public List orderByMarkDescending(); 25 | 26 | public List orderByMarkAscending(); 27 | /** 28 | * @return clusterize the students by their marks and return all the 29 | * students with the highest mark. 30 | * 31 | * Example: If Georgi and Ivo have 32 | * 6.0, but Radoslav has 5.0, you have to return Georgi and Ivo, but 33 | * not Radoslav 34 | */ 35 | public List getStudentsWithLowestMarks(); 36 | 37 | public List getStudentsWithHighestMarks(); 38 | 39 | /** 40 | * @return a map consisting of a List of marks per a given age, e.g. 41 | * result.get(20) would return the list of all the marks of the 42 | * students that are 20 years old. 43 | */ 44 | public Map> getMarksDistributionByAge(); 45 | 46 | public Map getAverageMarkByGender(); 47 | 48 | /** 49 | * example: Return a map that contains 50 | * 4.5 -> 3 times 51 | * 4.0 -> 2 times. 52 | * 2.0 -> 8 times. 53 | * @return 54 | */ 55 | public Map getMarksDistribution(); 56 | 57 | /** 58 | * @return "first@email.com, second@email.com, third@email.com..." 59 | */ 60 | public String getEmailToHeader(); 61 | 62 | 63 | /** 64 | * Split the students by their gender, and then partition them by their age 65 | */ 66 | public Map>> splitStudentMarksByGenderAndThenByAge(); 67 | } 68 | -------------------------------------------------------------------------------- /week14/3.Friday/Java8Problems/src/com/hackbulgaria/corejava101/data/Gender.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava101.data; 2 | 3 | public enum Gender { 4 | MALE, 5 | FEMALE, 6 | NOT_SURE 7 | } 8 | -------------------------------------------------------------------------------- /week14/3.Friday/Java8Problems/src/com/hackbulgaria/corejava101/data/Student.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava101.data; 2 | 3 | import java.util.Calendar; 4 | 5 | public class Student { 6 | private final String name; 7 | private final int age; 8 | private final double grade; 9 | private final Gender gender; 10 | 11 | /** 12 | * @param name 13 | * @param age 14 | * @param grade - between 2 and 6 15 | */ 16 | public Student(String name, int age, double grade, Gender gender){ 17 | this.name = name; 18 | this.age = age; 19 | this.grade = grade; 20 | this.gender = gender; 21 | } 22 | 23 | public String getName() { 24 | return name; 25 | } 26 | 27 | public int getAge() { 28 | return age; 29 | } 30 | 31 | public double getGrade() { 32 | return grade; 33 | } 34 | 35 | public Gender getGender() { 36 | return gender; 37 | } 38 | 39 | public String getEmail(){ 40 | return name + "_" + (Calendar.getInstance().get(Calendar.YEAR) - age) + "@gmail.com"; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /week14/3.Friday/Java8Problems/src/com/hackbulgaria/corejava101/data/StudentsDataFactory.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.corejava101.data; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class StudentsDataFactory { 7 | public static List getAllStudents(){ 8 | List students = new ArrayList(); 9 | students.add(new Student("Georgi", 19, 2.0f, Gender.MALE)); 10 | students.add(new Student("Dimitur", 21, 2.0f, Gender.MALE)); 11 | students.add(new Student("Vasil", 19, 2.0f, Gender.MALE)); 12 | 13 | students.add(new Student("Tihomir", 20, 3.0f, Gender.MALE)); 14 | students.add(new Student("Ivomir", 20, 3.0f, Gender.MALE)); 15 | students.add(new Student("Vladislav", 21, 3.0f, Gender.MALE)); 16 | 17 | students.add(new Student("Filip", 19, 3.5f, Gender.MALE)); 18 | students.add(new Student("Boris", 20, 3.5f, Gender.MALE)); 19 | 20 | students.add(new Student("Genady", 21, 4.0f, Gender.MALE)); 21 | students.add(new Student("Ivan", 21, 4.0f,Gender.MALE)); 22 | students.add(new Student("Elena", 21, 4.0f, Gender.FEMALE)); 23 | 24 | students.add(new Student("Radoslav", 22, 4.5f, Gender.MALE)); 25 | students.add(new Student("Maria", 22, 4.5f,Gender.FEMALE)); 26 | 27 | students.add(new Student("Teodor", 22, 5.0f,Gender.MALE)); 28 | students.add(new Student("Stanislava", 22, 5.0f, Gender.FEMALE)); 29 | 30 | students.add(new Student("Anton", 20, 5.5f, Gender.MALE)); 31 | students.add(new Student("Marina", 21, 5.5f, Gender.FEMALE)); 32 | students.add(new Student("Salfetka", 21, 5.5f, Gender.FEMALE)); 33 | students.add(new Student("Zlatina", 22, 5.5f, Gender.FEMALE)); 34 | 35 | students.add(new Student("Petar", 19, 6.0f, Gender.MALE)); 36 | students.add(new Student("Yanitsa", 21, 6.0f, Gender.FEMALE)); 37 | return students; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /week14/3.Friday/README.md: -------------------------------------------------------------------------------- 1 | ### Java 8 Problems 2 | 3 | Stream and lambda problems 4 | 1. Download and import the Java8 project to your eclipse or IntellIJ platforms 5 | 2. Subclass the `StudentOperations` interface and add all the methods so it compiles 6 | 3. Run the unit tests. Everything should fail. 7 | 8 | 4. Make them all green : ) 9 | 10 | Gotcha*: 11 | Create a functional interface, that would make the following code compile 12 | X x = () -> () -> () -> () -> () -> () -> () -> () -> () -> () -> () -> () -> () -> () -> () -> () -> null; 13 | 14 | Spliterator task: 15 | 'Spliterator' (`java.util.Spliterator`) is a new term from java8 - you can create streams by supplying spliterators. Spliterator is responsible for partitioning and object and advancing a stream. 16 | 17 | Implement a `SlidingWindowSpliterator` for collections. 18 | 19 | How to verify your spliterator is working correctly: 20 | 21 | ``` 22 | Collection testCollection = Arrays.asList("This","is","a","lame","example"); 23 | Spliterator yourSpliterator = new SlidingWindowSpliterator(testCollection, 2) //2 is the sliding window length 24 | StreamSupport.stream(yourSpliteratorObject).forEach(System.out::println); 25 | ``` 26 | ---- 27 | ``` 28 | This is 29 | is a 30 | a lame 31 | lame example 32 | ``` -------------------------------------------------------------------------------- /week14/3.Friday/prereading.md: -------------------------------------------------------------------------------- 1 | *On functional interfaces* 2 | http://java.dzone.com/articles/introduction-functional-1 3 | http://baddotrobot.com/blog/2014/04/07/functional-interfaces-in-java8/ 4 | Q: Give an example of an interface (or write a sane interface) that is not functional. 5 | Q: Which well known interface from Java 7 is a good candidate to be a functional interface? There are so many, pick one, it's enough. 6 | 7 | *On lambda expressions:* 8 | *Lambda expressions quick-start:* 9 | http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html 10 | http://viralpatel.net/blogs/lambda-expressions-java-tutorial/ 11 | 12 | *Stream API:* 13 | http://java.amitph.com/2014/01/understanding-java-8-streams-api.html 14 | http://java.amitph.com/2014/02/java-8-streams-api-intermediate.html#.VVJEQlSUe00 15 | http://java.amitph.com/2014/02/java-8-streams-api-terminal-operations.html#.VVJFU1SUe00 16 | 17 | -------------------------------------------------------------------------------- /week15/1.Monday/README.md: -------------------------------------------------------------------------------- 1 | # Interviews 2 | 3 | How to write your CV and find the best job for you. 4 | -------------------------------------------------------------------------------- /week16/Nat/README.md: -------------------------------------------------------------------------------- 1 | # Nat 2 | 3 | We are going to implement natural numbers without integers. This is called [Peano Arithmetic](https://en.wikipedia.org/wiki/Peano_axioms#Arithmetic) 4 | 5 | We are going to represent `0` with `Zero` and every number will be a successor of the previous. 6 | 7 | Few examples: 8 | 9 | ``` 10 | 1 = Succ(Zero) - One is the successor of zero 11 | 2 = Succ(Succ(Zero)) - Two is hte successor of the successor of zero. 12 | ``` 13 | 14 | ## Abstract Nat class 15 | 16 | We are going to have the following abstract base class: 17 | 18 | ```java 19 | public abstract class Nat { 20 | public abstract boolean isZero(); 21 | public abstract Nat next(); 22 | public abstract Nat prev(); 23 | public abstract Nat add(Nat b); 24 | public abstract Nat minus(Nat b); 25 | public abstract Integer toInt(); 26 | } 27 | ``` 28 | 29 | ## Zero and Succ 30 | 31 | Our task will be to implement the following subtypes of `Nat`: `class Zero extends Nat {}` and `class Succ extends Nat{}` 32 | -------------------------------------------------------------------------------- /week16/Nat/src/com/hackbulgaria/java101/nat/Nat.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.java101.nat; 2 | 3 | public abstract class Nat { 4 | public abstract boolean isZero(); 5 | 6 | public Nat next() { 7 | return new Succ(this); 8 | } 9 | 10 | public abstract Nat prev(); 11 | public abstract Nat add(Nat b); 12 | public abstract Nat minus(Nat b); 13 | public abstract Integer toInt(); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /week16/Nat/src/com/hackbulgaria/java101/nat/NatTest.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.java101.nat; 2 | 3 | public class NatTest { 4 | 5 | public static void main(String[] args) { 6 | Nat zero = new Zero(); 7 | Nat one = new Succ(zero); 8 | 9 | System.out.println(zero); 10 | System.out.println(zero.toInt()); 11 | System.out.println(one); 12 | System.out.println(one.toInt()); 13 | 14 | Nat two = one.add(one); 15 | System.out.println(two); 16 | 17 | System.out.println(two.minus(one)); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /week16/Nat/src/com/hackbulgaria/java101/nat/Succ.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.java101.nat; 2 | 3 | public class Succ extends Nat{ 4 | 5 | private Nat n; 6 | 7 | public Succ(Nat n) { 8 | this.n = n; 9 | } 10 | 11 | @Override 12 | public boolean isZero() { 13 | return false; 14 | } 15 | 16 | @Override 17 | public Nat prev() { 18 | return n; 19 | } 20 | 21 | @Override 22 | public Nat add(Nat b) { 23 | if(b.isZero()) { 24 | return this; 25 | } 26 | 27 | return this.next().add(b.prev()); 28 | } 29 | 30 | @Override 31 | public Nat minus(Nat b) { 32 | if(b.isZero()) { 33 | return this; 34 | } 35 | 36 | return this.prev().minus(b.prev()); 37 | } 38 | 39 | @Override 40 | public Integer toInt() { 41 | return 1 + prev().toInt(); 42 | } 43 | 44 | @Override 45 | public String toString() { 46 | return "Succ + " + prev().toString(); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /week16/Nat/src/com/hackbulgaria/java101/nat/Zero.java: -------------------------------------------------------------------------------- 1 | package com.hackbulgaria.java101.nat; 2 | 3 | public class Zero extends Nat{ 4 | 5 | @Override 6 | public boolean isZero() { 7 | return true; 8 | } 9 | 10 | @Override 11 | public Nat prev() { 12 | throw new ArithmeticException("Can go beyound 0."); 13 | } 14 | 15 | @Override 16 | public Nat add(Nat b) { 17 | return b; 18 | } 19 | 20 | @Override 21 | public Nat minus(Nat b) { 22 | throw new ArithmeticException("Can go beyound 0."); 23 | } 24 | 25 | @Override 26 | public Integer toInt() { 27 | return 0; 28 | } 29 | 30 | @Override 31 | public String toString() { 32 | return "Zero"; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /week16/Polynomials/README.md: -------------------------------------------------------------------------------- 1 | # Polynomial 2 | 3 | ## What is a polynomial? 4 | 5 | In mathematics, a polynomial is an expression consisting of variables and coefficients which only employs the operations of addition, subtraction, multiplication, and non-negative integer exponents. 6 | 7 | ... but you don't need all that for this task. 8 | 9 | A polynomial is an expression of the following type: 10 | 11 | * x2 - 4x + 7 12 | * 2x4 + 3x2 - 10x + 3 13 | * 4x10 - 7x9 + 5x8 ...... - 3x2 + 8x + 5 14 | * Anxn + An-1xn-1 + An-2xn-2 + ... + A2x2 + A1x1 + A0x0 (... if that explains it better) 15 | 16 | At the moment we're interested in Polynomials with only one variable. 17 | 18 | ## The task 19 | 20 | ### 1. Requirements 21 | 22 | Model a Java program that handles Polynomials. 23 | 24 | * Add, substract and multiplicate Polynomials 25 | * `P1 + P2 = P3` where P3 is a result polynom 26 | * `P1 - P2 = P3` where P3 is a result polynom 27 | * `P1 * P2 = P3` where P3 is a result polynom 28 | * Method for multiplicating the polynomial by a constant 29 | * `P1 * c = P3` where c is a constant and P3 is a result polynom 30 | * Method for returning the first derivative of a Polynomial 31 | * `(P1)' = P3` where P3 is a polynom and is the first derivative of P1 32 | * For example the Polynomial `2x^4 + 3x^2 - 10x + 3` has a first derivative `8x^3 + 6x - 10` 33 | * Method for evaluating a Polynomial 34 | * The Polynomial should be **immutable** 35 | * The Polynomial should be parametrised by a Generic type that is a valid number. For example Integer or Double 36 | 37 | ### 2. Hints 38 | 39 | Implementing the following methods will probably make your task easier: 40 | 41 | * `add(..)` for adding a member to the polynomial 42 | * `fromString("..")` a static method to return a polynomial from a string 43 | * For example the string `2x^4 + 3x^2 - 10x + 3` 44 | 45 | ### 3. Write tests 46 | 47 | Validate your program by writing some tests -------------------------------------------------------------------------------- /week16/threading/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | io.github.ivanvergiliev 6 | threading 7 | 1.0-SNAPSHOT 8 | jar 9 | 10 | threading 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | junit 20 | junit 21 | 3.8.1 22 | test 23 | 24 | 25 | 26 | 27 | 28 | 29 | org.apache.maven.plugins 30 | maven-compiler-plugin 31 | 3.5.1 32 | 33 | 1.8 34 | 1.8 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/FalseSharing.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | import java.util.concurrent.atomic.AtomicLongArray; 4 | 5 | public class FalseSharing { 6 | private static final long MAX_ITER = 20_000_000L; 7 | 8 | private static AtomicLongArray arr = new AtomicLongArray(100); 9 | 10 | public static class Incrementer implements Runnable { 11 | private int index; 12 | 13 | public Incrementer(int index) { 14 | this.index = index; 15 | } 16 | 17 | public void run() { 18 | for (long i = 0; i < MAX_ITER; ++i) { 19 | arr.addAndGet(index, i); 20 | } 21 | } 22 | } 23 | 24 | public static void main(String[] args) throws InterruptedException { 25 | while (true) { 26 | // False sharing. 27 | System.out.println("False sharing execution time: " + runtimeForPositions(0, 1)); 28 | 29 | // No false sharing. 30 | System.out.println("Actual execution time: " + runtimeForPositions(20, 80)); 31 | } 32 | } 33 | 34 | private static double runtimeForPositions(int p1, int p2) throws InterruptedException { 35 | long startTime = System.nanoTime(); 36 | Thread t1 = new Thread(new Incrementer(p1)); 37 | Thread t2 = new Thread(new Incrementer(p2)); 38 | t1.start(); 39 | t2.start(); 40 | t1.join(); 41 | t2.join(); 42 | System.out.println(arr.get(p1) + arr.get(p2)); 43 | return (System.nanoTime() - startTime) / 1e9; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/FirstCompletedFutures.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | import java.util.concurrent.CompletableFuture; 4 | import java.util.stream.LongStream; 5 | 6 | public class FirstCompletedFutures { 7 | 8 | public static void main(String[] args) { 9 | CompletableFuture f1 = CompletableFuture 10 | .supplyAsync(() -> { 11 | return LongStream 12 | .range(1, (long) 1e9).sum(); 13 | }); 14 | CompletableFuture f2 = CompletableFuture 15 | .supplyAsync(() -> { 16 | return LongStream 17 | .range((long) 1e9, (long) 1.37e9) 18 | .reduce(1, (a, b) -> (a + b) % 1337); 19 | }); 20 | f1.acceptEitherAsync(f2, System.out::println) 21 | .join(); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/FirstCompletedThreads.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | import java.util.concurrent.CountDownLatch; 4 | import java.util.concurrent.atomic.AtomicLong; 5 | import java.util.stream.LongStream; 6 | 7 | public class FirstCompletedThreads { 8 | 9 | public static void main(String[] args) throws InterruptedException { 10 | CountDownLatch resultComputed = new CountDownLatch(1); 11 | AtomicLong result = new AtomicLong(); 12 | Thread t1 = new Thread(() -> { 13 | long localResult = LongStream.range(1, (long) 1e9).sum(); 14 | result.compareAndSet(0, localResult); 15 | // What if local result can be 0? 16 | resultComputed.countDown(); 17 | }); 18 | Thread t2 = new Thread(() -> { 19 | long localResult = LongStream.range((long) 1e9, (long) 1.37e9) 20 | .reduce(1, (a, b) -> (a + b) % 1337); 21 | result.compareAndSet(0, localResult); 22 | resultComputed.countDown(); 23 | }); 24 | t1.start(); 25 | t2.start(); 26 | resultComputed.await(); 27 | System.out.println(result); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/ForEachProgression.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.function.Consumer; 6 | 7 | public class ForEachProgression { 8 | 9 | public static void main(String[] args) { 10 | List l = Arrays.asList("one", "two", "four", "eight"); 11 | 12 | for (int i = 0; i < l.size(); ++i) { 13 | System.out.println(l.get(i)); 14 | } 15 | 16 | for (String s : l) { 17 | System.out.println(s); 18 | } 19 | 20 | l.forEach(new Consumer() { 21 | public void accept(String s) { 22 | System.out.println(s); 23 | } 24 | }); 25 | 26 | // lambda expression 27 | l.forEach(s -> System.out.println(s)); 28 | 29 | // method reference - "use the method println(String) on the System.out object 30 | // and apply it to each element of this list." 31 | l.forEach(System.out::println); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/LockUsage.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | import java.util.concurrent.locks.Lock; 4 | import java.util.concurrent.locks.ReentrantLock; 5 | 6 | public class LockUsage { 7 | 8 | static Lock l = new ReentrantLock(); 9 | 10 | public static void main(String[] args) { 11 | l.lock(); 12 | try { 13 | // Do something exclusive. 14 | } finally { 15 | l.unlock(); 16 | } 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/NonVolatileFlag.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | public class NonVolatileFlag { 4 | private static boolean flag = false; 5 | 6 | public static class FlagChecker implements Runnable { 7 | public void run() { 8 | @SuppressWarnings("unused") 9 | long iter = 0; // Used for debugging in order to determine the number of iterations so far. 10 | while (flag == false) { 11 | ++iter; 12 | // Wait and do nothing. 13 | } 14 | } 15 | } 16 | 17 | public static class FlagSetter implements Runnable { 18 | public void run() { 19 | int count = 0; 20 | while (true) { 21 | ++count; 22 | if (count > 100_000) { 23 | break; 24 | } 25 | } 26 | flag = true; 27 | } 28 | } 29 | 30 | public static void main(String[] args) throws InterruptedException { 31 | for (int i = 0; ; ++i) { 32 | System.out.println("Running iteration " + i); 33 | flag = false; 34 | Thread checker = new Thread(new FlagChecker()); 35 | Thread setter = new Thread(new FlagSetter()); 36 | checker.start(); 37 | setter.start(); 38 | checker.join(); 39 | } 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/ParallelSumFutures.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.concurrent.CompletableFuture; 6 | import java.util.stream.Collectors; 7 | import java.util.stream.LongStream; 8 | 9 | public class ParallelSumFutures { 10 | private static final int BATCH_SIZE = 100_000; 11 | 12 | public static void main(String[] args) throws InterruptedException { 13 | List numbers = LongStream.range(0, (long) 1e7).boxed().collect(Collectors.toList()); 14 | List> futures = new ArrayList<>(); 15 | for (int start = 0; start < numbers.size(); start += BATCH_SIZE) { 16 | int from = start; 17 | int to = Math.min(start + BATCH_SIZE, numbers.size()); 18 | CompletableFuture f = CompletableFuture.supplyAsync(() -> { 19 | return numbers.subList(from, to).stream().reduce(0L, (x, y) -> x + y); 20 | }); 21 | futures.add(f); 22 | } 23 | long result = futures.stream() 24 | .map(future -> future.join()) 25 | .reduce(0L, (x, y) -> x + y); 26 | System.out.println(result); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/ParallelSumStream.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | import java.util.List; 4 | import java.util.stream.Collectors; 5 | import java.util.stream.LongStream; 6 | 7 | public class ParallelSumStream { 8 | public static void main(String[] args) throws InterruptedException { 9 | List numbers = LongStream.range(0, (long) 1e7).boxed().collect(Collectors.toList()); 10 | long result = numbers.parallelStream().reduce(0L, (x, y) -> x + y); 11 | System.out.println(result); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/ParallelSumThreads.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.concurrent.atomic.LongAdder; 6 | import java.util.stream.Collectors; 7 | import java.util.stream.LongStream; 8 | 9 | public class ParallelSumThreads { 10 | private static final int BATCH_SIZE = 100_000; 11 | 12 | public static class PartialSumComputer implements Runnable { 13 | private List numbers; 14 | private int from; 15 | private int to; 16 | 17 | private LongAdder result; 18 | 19 | public PartialSumComputer(List numbers, int from, int to, LongAdder result) { 20 | this.numbers = numbers; 21 | this.from = from; 22 | this.to = to; 23 | this.result = result; 24 | } 25 | 26 | public void run() { 27 | for (int i = from; i < to; ++i) { 28 | result.add(numbers.get(i)); 29 | } 30 | } 31 | } 32 | 33 | public static void main(String[] args) throws InterruptedException { 34 | List numbers = LongStream.range(0, (long) 1e7).boxed().collect(Collectors.toList()); 35 | List threads = new ArrayList<>(); 36 | LongAdder result = new LongAdder(); 37 | for (int start = 0; start < numbers.size(); start += BATCH_SIZE) { 38 | int end = Math.min(start + BATCH_SIZE, numbers.size()); 39 | Thread t = new Thread(new PartialSumComputer(numbers, start, end, result)); 40 | t.start(); 41 | threads.add(t); 42 | } 43 | for (Thread t : threads) { 44 | t.join(); 45 | } 46 | System.out.println(result.sum()); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/ParallelSumThreadsLambda.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.concurrent.atomic.LongAdder; 6 | import java.util.stream.Collectors; 7 | import java.util.stream.LongStream; 8 | 9 | public class ParallelSumThreadsLambda { 10 | private static final int BATCH_SIZE = 100_000; 11 | 12 | public static void main(String[] args) throws InterruptedException { 13 | List numbers = LongStream.range(0, (long) 1e7).boxed().collect(Collectors.toList()); 14 | List threads = new ArrayList<>(); 15 | LongAdder result = new LongAdder(); 16 | for (int start = 0; start < numbers.size(); start += BATCH_SIZE) { 17 | int from = start; 18 | int to = Math.min(start + BATCH_SIZE, numbers.size()); 19 | Thread t = new Thread(() -> { 20 | for (int i = from; i < to; ++i) { 21 | result.add(numbers.get(i)); 22 | } 23 | }); 24 | t.start(); 25 | threads.add(t); 26 | } 27 | for (Thread t : threads) { 28 | t.join(); 29 | } 30 | System.out.println(result.sum()); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/SortByLength.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | import java.util.Comparator; 6 | import java.util.List; 7 | 8 | public class SortByLength { 9 | 10 | public static void main(String[] args) { 11 | List l = Arrays.asList("eighteen", "three", "two", "four", "million", "1 billion"); 12 | Collections.sort(l, new Comparator() { 13 | public int compare(String a, String b) { 14 | return Integer.compare(a.length(), b.length()); 15 | } 16 | }); 17 | l.forEach(System.out::println); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/SortByLengthLambda.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | public class SortByLengthLambda { 8 | 9 | public static void main(String[] args) { 10 | List l = Arrays.asList("eighteen", "three", "two", "four", "million", "1 billion"); 11 | Collections.sort(l, (a, b) -> Integer.compare(a.length(), b.length())); 12 | l.forEach(System.out::println); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/StreamJava7.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | import java.util.stream.Collectors; 6 | 7 | public class StreamJava7 { 8 | 9 | public static void main(String[] args) { 10 | List input = Arrays.asList("eighteen", "three", "two", "four", "million", "1 billion"); 11 | String result = input.stream() 12 | .filter(s -> s.contains("o")) 13 | .sorted((a, b) -> Integer.compare(a.length(), b.length())) 14 | .collect(Collectors.joining("; ")); 15 | System.out.println(result); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/StreamJava8.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.Collections; 6 | import java.util.List; 7 | 8 | public class StreamJava8 { 9 | 10 | public static void main(String[] args) { 11 | List input = Arrays.asList("eighteen", "three", "two", "four", "million", "1 billion"); 12 | List filtered = new ArrayList<>(); 13 | for (String s : input) { 14 | if (s.contains("o")) { 15 | filtered.add(s); 16 | } 17 | } 18 | Collections.sort(filtered, (a, b) -> Integer.compare(a.length(), b.length())); 19 | 20 | String result = ""; 21 | boolean shouldAddSemicolon = false; 22 | for (String s : filtered) { 23 | if (shouldAddSemicolon) { 24 | result += "; "; 25 | } 26 | shouldAddSemicolon = true; 27 | result += s; 28 | } 29 | System.out.println(result); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/SumPlusEquals.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class SumPlusEquals { 7 | private static int sum = 0; 8 | 9 | public static class RunnableImpl implements Runnable { 10 | public void run() { 11 | for (int i = 0; i < 1000; ++i) { 12 | sum += 1; 13 | } 14 | } 15 | } 16 | 17 | public static void main(String[] args) throws InterruptedException { 18 | List threads = new ArrayList<>(); 19 | for (int i = 0; i < 100; ++i) { 20 | Thread t = new Thread(new RunnableImpl()); 21 | t.start(); 22 | threads.add(t); 23 | } 24 | for (Thread t : threads) { 25 | t.join(); 26 | } 27 | System.out.println(sum); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/SumPlusPlus.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class SumPlusPlus { 7 | private static int sum = 0; 8 | 9 | public static class RunnableImpl implements Runnable { 10 | public void run() { 11 | for (int i = 0; i < 1000; ++i) { 12 | ++sum; 13 | } 14 | } 15 | } 16 | 17 | public static void main(String[] args) throws InterruptedException { 18 | List threads = new ArrayList<>(); 19 | for (int i = 0; i < 100; ++i) { 20 | Thread t = new Thread(new RunnableImpl()); 21 | t.start(); 22 | threads.add(t); 23 | } 24 | for (Thread t : threads) { 25 | t.join(); 26 | } 27 | System.out.println(sum); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/ThreadSafeAdder.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class ThreadSafeAdder { 7 | private int sum = 0; 8 | 9 | public synchronized void increment() { 10 | ++sum; 11 | } 12 | 13 | public synchronized int getSum() { 14 | return sum; 15 | } 16 | 17 | public static class RunnableImpl implements Runnable { 18 | private ThreadSafeAdder adder; 19 | 20 | public RunnableImpl(ThreadSafeAdder adder) { 21 | this.adder = adder; 22 | } 23 | 24 | public void run() { 25 | for (int i = 0; i < 1000; ++i) { 26 | adder.increment(); 27 | } 28 | } 29 | } 30 | 31 | public static void main(String[] args) throws InterruptedException { 32 | List threads = new ArrayList<>(); 33 | ThreadSafeAdder adder = new ThreadSafeAdder(); 34 | for (int i = 0; i < 100; ++i) { 35 | Thread t = new Thread(new RunnableImpl(adder)); 36 | t.start(); 37 | threads.add(t); 38 | } 39 | for (Thread t : threads) { 40 | t.join(); 41 | } 42 | System.out.println(adder.getSum()); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/ThreadSafeFibonacciAdder.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | import java.io.IOException; 4 | import java.io.OutputStream; 5 | import java.io.PrintStream; 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | public class ThreadSafeFibonacciAdder { 10 | private int sum = 0; 11 | 12 | public void add(int pos) { 13 | int a = 1; 14 | int b = 1; 15 | for (int n = 3; n <= pos; ++n) { 16 | int c = a + b; 17 | a = b; 18 | b = c; 19 | } 20 | synchronized (this) { 21 | sum += b; 22 | } 23 | } 24 | 25 | public synchronized int getSum() { 26 | return sum; 27 | } 28 | 29 | public static class RunnableImpl implements Runnable { 30 | private ThreadSafeFibonacciAdder adder; 31 | 32 | public RunnableImpl(ThreadSafeFibonacciAdder adder) { 33 | this.adder = adder; 34 | } 35 | 36 | public void run() { 37 | for (int i = 0; i < 10_000_000; ++i) { 38 | adder.add(i % 50); 39 | } 40 | } 41 | } 42 | 43 | public static void main(String[] args) throws InterruptedException { 44 | System.setOut(new PrintStream(new OutputStream() { 45 | @Override public void write(int b) throws IOException {} 46 | })); 47 | long start = System.nanoTime(); 48 | List threads = new ArrayList<>(); 49 | ThreadSafeFibonacciAdder adder = new ThreadSafeFibonacciAdder(); 50 | for (int i = 0; i < 4; ++i) { 51 | Thread t = new Thread(new RunnableImpl(adder)); 52 | t.start(); 53 | threads.add(t); 54 | } 55 | for (Thread t : threads) { 56 | t.join(); 57 | } 58 | System.err.println(adder.getSum()); 59 | System.err.println("Execution time: " + (System.nanoTime() - start) / 1e9); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/Unjoined.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | public class Unjoined { 4 | 5 | public static class RunnableImpl implements Runnable { 6 | public void run() { 7 | for (int i = 0; i < 100; ++i) { 8 | System.out.println("line " + i); 9 | } 10 | } 11 | } 12 | 13 | public static void main(String[] args) { 14 | Thread t = new Thread(new RunnableImpl()); 15 | t.start(); 16 | System.out.println("started thread"); 17 | // Start is asynchronous. 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/Unjoined1.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | public class Unjoined1 { 4 | 5 | public static class RunnableImpl implements Runnable { 6 | public void run() { 7 | for (int i = 0; i < 100; ++i) { 8 | System.out.println("line " + i); 9 | } 10 | } 11 | } 12 | 13 | public static void main(String[] args) throws InterruptedException { 14 | Thread t = new Thread(new RunnableImpl()); 15 | t.start(); 16 | t.join(); 17 | System.out.println("after thread"); 18 | // Start is asynchronous. => Need to use Thread.join() to wait for a thread to finish. 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/Unordered.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | public class Unordered { 4 | 5 | public static class RunnableImpl implements Runnable { 6 | private int id; 7 | 8 | public RunnableImpl(int id) { 9 | this.id = id; 10 | } 11 | 12 | public void run() { 13 | System.out.println("Executing runnable with id " + id); 14 | } 15 | } 16 | 17 | public static void main(String[] args) { 18 | for (int i = 0; i < 11; ++i) { 19 | Thread t = new Thread(new RunnableImpl(i)); 20 | t.start(); 21 | } 22 | 23 | // Threads don't run in the order you've started them. 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/UnorderedInterleaved.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | public class UnorderedInterleaved { 4 | 5 | public static class RunnableImpl implements Runnable { 6 | private int id; 7 | 8 | public RunnableImpl(int id) { 9 | this.id = id; 10 | } 11 | 12 | public void run() { 13 | for (int i = 0; i < 10; ++i) { 14 | System.out.println("Thread " + id + ", line " + i); 15 | } 16 | } 17 | } 18 | 19 | public static void main(String[] args) { 20 | System.out.println("starting..."); 21 | for (int i = 0; i < 10; ++i) { 22 | Thread t = new Thread(new RunnableImpl(i)); 23 | t.start(); 24 | } 25 | System.out.println("After all"); 26 | 27 | // Thread execution is interleaved - preemptive multitasking. 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/UnorderedJoinAll.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class UnorderedJoinAll { 7 | 8 | public static class RunnableImpl implements Runnable { 9 | private int id; 10 | 11 | public RunnableImpl(int id) { 12 | this.id = id; 13 | } 14 | 15 | public void run() { 16 | for (int i = 0; i < 10; ++i) { 17 | System.out.println("Thread " + id + ", line " + i); 18 | } 19 | } 20 | } 21 | 22 | public static void main(String[] args) throws InterruptedException { 23 | System.out.println("starting..."); 24 | List threads = new ArrayList<>(); 25 | for (int i = 0; i < 10; ++i) { 26 | Thread t = new Thread(new RunnableImpl(i)); 27 | t.start(); 28 | threads.add(t); 29 | } 30 | for (Thread t : threads) { 31 | t.join(); 32 | } 33 | System.out.println("After all"); 34 | // Joining each thread immediately after it's started eliminates parallelism. 35 | // => Need to start each thread asynchronously, then join each of them. 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /week16/threading/src/main/java/io/github/ivanvergiliev/UnorderedJoinImmediately.java: -------------------------------------------------------------------------------- 1 | package io.github.ivanvergiliev; 2 | 3 | public class UnorderedJoinImmediately { 4 | 5 | public static class RunnableImpl implements Runnable { 6 | private int id; 7 | 8 | public RunnableImpl(int id) { 9 | this.id = id; 10 | } 11 | 12 | public void run() { 13 | for (int i = 0; i < 10; ++i) { 14 | System.out.println("Thread " + id + ", line " + i); 15 | } 16 | } 17 | } 18 | 19 | public static void main(String[] args) throws InterruptedException { 20 | System.out.println("starting..."); 21 | for (int i = 0; i < 10; ++i) { 22 | Thread t = new Thread(new RunnableImpl(i)); 23 | t.start(); 24 | t.join(); 25 | } 26 | System.out.println("After all"); 27 | // Joining each thread immediately after it's started eliminates parallelism. 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /week17/1.Tuesday/bonus_task.md: -------------------------------------------------------------------------------- 1 | В кухнята на ресторант има n котлона. За приготвянето на една мекица на всеки от тези котлони са необходими съответно t1, t2, …, tn секунди. 2 | 3 | Напишете програма, която намира най-малко за колко секунди може да се приготвят x мекици. За пърженето на една мекица може да се използва само един котлон. 4 | 5 | ## Input Format 6 | 7 | От първия ред се въвежда броя на тестовите примери. От първия ред на всеки от тях се въвеждат броят на мекиците x (0 < x < 1015) и броят на котлоните n (0 < n < 20). От втория ред се въвеждат n цели положителни числа, по-малки от 500 – времената t1, t2, …, tn. 8 | 9 | ## Output Format 10 | 11 | За всеки тестов пример на отделен ред програмата трябва да изведе минималното време, за което може да се приготвят мекиците. 12 | 13 | 14 | ## Sample Input 15 | 16 | 1 17 | 18 | 3 2 19 | 20 | 50 70 21 | 22 | 23 | ## Sample Output 24 | 25 | 100 -------------------------------------------------------------------------------- /week17/1.Tuesday/complexities.md: -------------------------------------------------------------------------------- 1 | # Complexities 2 | 3 | Write down the asymptotic complexities of the following functions: 4 | 5 | ## Checking if a number is prime 6 | 7 | ``` 8 | is_prime(number) { 9 | for (i = 2; i < number; i++) { 10 | if (number % i == 0) { 11 | return false 12 | } 13 | } 14 | return true 15 | } 16 | ``` 17 | 18 | Complexity: ... 19 | 20 | ## Checking if a string is palindrome 21 | 22 | ``` 23 | is_palindrome(string) { 24 | n = length(string) 25 | 26 | i = 0 27 | j = n - 1 28 | while (i < j) { 29 | if (string[i] != string[j]) { 30 | return false 31 | } 32 | i = i + 1 33 | j = j - 1 34 | } 35 | 36 | return true 37 | } 38 | ``` 39 | 40 | Complexity: ... 41 | 42 | ## Summing elements of a matrix 43 | 44 | ``` 45 | for (i = 0; i < n; i++) { 46 | for (j = 0; j < m; j++) { 47 | sum += numbers[i][j] 48 | } 49 | } 50 | ``` 51 | 52 | Complexity: ... 53 | 54 | ## Counting 1 55 | 56 | ``` 57 | for (i = 0; i < n; i++) { 58 | for (j = i; j < n; j++) { 59 | count++ 60 | } 61 | } 62 | ``` 63 | 64 | Complexity: ... 65 | 66 | ## Counting 2 67 | 68 | ``` 69 | for (i = 0; i < n; i++) { 70 | for (j = 1; j < n; j*=2) { 71 | count++ 72 | } 73 | } 74 | ``` 75 | 76 | Complexity: ... 77 | -------------------------------------------------------------------------------- /week17/1.Tuesday/prereadings/searching.md: -------------------------------------------------------------------------------- 1 | # Searching 2 | 3 | ## Linear search 4 | 5 | A trivial way of finding an element in a sequence is looking at 6 | every element of the sequence. If the collection does not imply some 7 | specific ordering this could be the only way of searching. However, 8 | large collection will definitely cause a performance impact. 9 | 10 | ## Binary search 11 | 12 | [Binary search](https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/) 13 | is an example of an algorithm that with some amount of 14 | preprocessing is able to solve a hard problem. Sorting a collection 15 | of elements allows consecutive searches to be really fast. 16 | 17 | The strategy that this algorithm employs is very similar to the one 18 | we saw in merge sort and quick sort. 19 | 20 | You can go through each step of the algorithm [here](http://www.cs.armstrong.edu/liang/animation/web/BinarySearch.html). 21 | 22 | ## Interpolation search 23 | 24 | Can we search faster than binary? Yes, if we once again limit the problem 25 | and require knowledge about the range of the values in the searched interval. 26 | If that's the case [Interpolation search](http://www.stoimen.com/blog/2012/01/02/computer-algorithms-interpolation-search/) 27 | does a pretty good job improving the performance of binary search. 28 | -------------------------------------------------------------------------------- /week17/1.Tuesday/prereadings/sorting.md: -------------------------------------------------------------------------------- 1 | # Sorting 2 | 3 | Sorting a sequence of elements is a well-known problem with many solutions. 4 | We could learn a lot just by looking at the steps that different algorithms 5 | take to produce a solution. 6 | 7 | ## Selection sort 8 | 9 | [Selection sort](http://en.wikipedia.org/wiki/Selection_sort) is probably 10 | the simplest way of sorting a collection - take the minimum element and 11 | put in the first postion, take the next smallest element and put it next 12 | to the previous. Do this for all elements and you have a sorted collection! 13 | [Here](http://courses.cs.vt.edu/~csonline/Algorithms/Lessons/SelectionSort/index.html) 14 | is a description of the steps of the algorithm. 15 | [Here](https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html) 16 | you can find a nice visualization of the steps of the algorithm. 17 | 18 | ## Insertion sort 19 | 20 | [Insertion sort](http://en.wikipedia.org/wiki/Insertion_sort) builds the 21 | sorted array by constantly adding elements to it in the correct position. 22 | [Here](http://courses.cs.vt.edu/csonline/Algorithms/Lessons/InsertionSort/index.html) 23 | is a description of the steps of the algorithm. 24 | [Here](https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html) 25 | you can find a nice visualization of the steps of the algorithm. 26 | 27 | ## Merge sort 28 | 29 | [Merge sort](http://en.wikipedia.org/wiki/Merge_sort) is a nice way of sorting 30 | a sequence of elements. It is a divide and conquer algorithm that divides the 31 | problem in smaller parts, solves them separately and then combines the solutions 32 | to produce a result. 33 | [Here](https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html) 34 | you can find a nice visualization of the steps of the algorithm. 35 | 36 | ## Bubble sort 37 | 38 | [Bubble sort](http://en.wikipedia.org/wiki/Bubble_sort) produces a sorted sequence 39 | by comparing and swapping adjacent elements. 40 | [Here](https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html) 41 | you can find a nice visualization of the steps of the algorithm. 42 | 43 | ## Counting sort 44 | 45 | [Counting sort](http://en.wikipedia.org/wiki/Counting_sort) is a genious algorithm 46 | that exploits the fact that arrays allow us to make n-way decisions (not just binary 47 | like if/else) to improve the performance for certain sequences. 48 | [Here](https://www.cs.usfca.edu/~galles/visualization/CountingSort.html) 49 | you can find a nice visualization of the steps it executes. 50 | -------------------------------------------------------------------------------- /week17/1.Tuesday/tasks.md: -------------------------------------------------------------------------------- 1 | # Tasks 2 | 3 | 4 | ## Binary Search 5 | Implement a binary search function. 6 | It should receive a list of elements that implement the comparable interface. 7 | It should return a true if the element is contained, false otherwise. 8 | 9 | 10 | ## Implement Counting sort 11 | 12 | Create a counting sort function. 13 | It should receive a List of Integers. 14 | It should return a new List containing the same integers but sorted in descending order. 15 | 16 | 17 | ## Implement Merge sort 18 | 19 | Implement the merge sort algorithm. 20 | It should receive an array/list of Integers. 21 | It should rearrange the input numbers. 22 | 23 | 24 | ## Improve your algorithm 25 | 26 | Improve your sorting algorithm. 27 | 28 | It may be good idea if the number of input elements are less than 32 for example to use other sorting algorithm. Use bubble sort or insertion sort for example. 29 | 30 | It may also be good idea to use bubble sort or insertion sort for example when the merge sort tries to sort parts of the array that are smallar than 32. 31 | 32 | 33 | ## Lets use Generics again 34 | 35 | Now when you have ultra-mega-giga cool sorting function you want to use it on not just numbers, but anything that is comparable. 36 | 37 | Rewrite your sorting function so that it uses generics. 38 | -------------------------------------------------------------------------------- /week17/2.Thursday/Build-Scripts.md: -------------------------------------------------------------------------------- 1 | # Build Scripts 2 | 3 | You are working on a build tool, similar to Apache [ANT](http://ant.apache.org/) 4 | , [make](https://www.gnu.org/software/make/), or [MSBuild](https://github.com/Microsoft/msbuild) 5 | , which builds and links projects into executables. Your tool will be given 6 | a list of projects to compile. Each project may have dependencies on the 7 | projects (i.e. it requires them to be build first before it can build). 8 | 9 | Your task is to determine the order in which the projects should be built 10 | so that it is ensured that all dependencies of a project will be built 11 | before the project itself. 12 | 13 | ## Input 14 | 15 | The first line will contain a single integer N - the number of projects to 16 | build. The second line will contain N strings - the names of the projects. 17 | The next line will contain the project you want to build. On each of the 18 | following N lines, on the i-th line there will be a single integer Mi, 19 | followed by Mi strings which describe the projects on which project i 20 | is dependent. 21 | 22 | ## Output 23 | 24 | On a single line on the standard output, print the space-separated names 25 | of the projects in the exact order in which they should be built. If there 26 | is no way to build the projects (i.e. they have circular dependencies), 27 | print "BUILD ERROR" (without the quotes). 28 | 29 | ## Limits 30 | 31 | ``` 32 | 1 <= N <= 50000 33 | ``` 34 | 35 | ## Example 36 | 37 | Input: 38 | 39 | ``` 40 | 5 41 | Extensions Interface Core Common Networking 42 | Interface 43 | 3 Common Core Networking 44 | 4 Core Common Extensions Networking 45 | 0 46 | 1 Core 47 | 2 Core Common 48 | ``` 49 | 50 | Output: 51 | 52 | ``` 53 | Core Common Networking Extensions Interface 54 | ``` 55 | -------------------------------------------------------------------------------- /week17/2.Thursday/Closest-Coffee-Store.md: -------------------------------------------------------------------------------- 1 | # Closest Coffee Store 2 | 3 | Implement a function in [Java](ClosestCoffeeStore.java), [Python](closest_coffee_store.py) 4 | or [C++](closest_coffee_store.cpp) that given a graph of connected points 5 | of interests and a starting point returns the closest coffee store to that 6 | point. Return `-1` in case there is no reachable coffee store from this location. 7 | 8 | ## Example 9 | 10 | Input: 11 | 12 | ``` 13 | The graph matrix: 14 | 15 | 0 1 2 3 4 5 16 | --------------- 17 | 0 | 0 1 0 1 0 0 18 | 1 | 1 0 1 0 0 0 19 | 2 | 0 1 0 0 1 0 20 | 3 | 1 0 0 0 0 0 21 | 4 | 0 0 1 0 0 1 22 | 5 | 0 0 0 0 1 0 23 | 24 | The coffee store property array: 25 | [0, 0, 1, 0, 0, 1] 26 | 27 | Starting point: 0 28 | ``` 29 | 30 | Output: 31 | 32 | ``` 33 | 2 # Because the nearest coffee store to `0` is `2` and the path to 34 | it is `0 -> 1 -> 2`. 35 | ``` 36 | -------------------------------------------------------------------------------- /week17/2.Thursday/Phone-Numbers.md: -------------------------------------------------------------------------------- 1 | # Phone Numbers 2 | 3 | You, as a leacturer of the algorithms class, have to call all the students to 4 | notify them that the class on Monday will not be held. However, calling each 5 | student individually will enormously increase your phone bills. 6 | 7 | You have a list of the phone numbers of all of the students. For each of the 8 | students, you also have the list of phone numbers of other students he or she 9 | has. Your genius plan to save on phone bills is to only call some of the 10 | students and tell them to call the others. 11 | 12 | What is the minimum number of phone calls you need to make in order to ensure 13 | that each student will be notified. 14 | 15 | Implement a function in [Java](PhoneNumbers.java), [Python](phone_numbers.py) 16 | or [C++](phone_numbers.cpp) which finds that number. 17 | 18 | ## Input 19 | 20 | On the first line of the standard input, there will be one integer - N - the 21 | number of students. On the next line there will be N space separated integers 22 | in the range [1; 1 000] - each representing the phone number of the 23 | i-th student. The following N lines will start with a single integer M and 24 | will be followed by M phone numbers - the i-th line will represent the list 25 | of contacts the i-th student has. 26 | 27 | It is guaranteed that if student i has the number of student j, student j 28 | also has the number of student i because they are considered to be friends. 29 | 30 | ## Output 31 | 32 | Output a single integer - the minimum number of calls you need to make. 33 | 34 | ## Limits 35 | 36 | ``` 37 | 1 <= N <= 1000 38 | 0 <= M <= 1000 39 | ``` 40 | 41 | ## Example 42 | 43 | Input: 44 | 45 | ``` 46 | 6 47 | 100 200 300 400 500 600 48 | 2 200 300 49 | 2 100 300 50 | 2 100 200 51 | 1 500 52 | 1 400 53 | 0 54 | ``` 55 | 56 | Output: 57 | 58 | ``` 59 | 3 60 | ``` 61 | -------------------------------------------------------------------------------- /week17/2.Thursday/Valid-Directories.md: -------------------------------------------------------------------------------- 1 | # Valid Directories 2 | 3 | Implement a function in [Java](GraphCycle.java), [Python](graph_cycle.py) 4 | or [C++](graph_cycle.cpp) that checks if a collection of directories and files 5 | is valid. 6 | 7 | A valid collection of directories and files is one that does not allow a path 8 | starting from directory and visiting its children to end in the same directory. 9 | 10 | The input is an adjacency matrix of the graph of directories and files. 11 | The values in the matrix symbolize different type of relations. For 12 | `graph[a][b]` the possible values are: 13 | 14 | * `0` - There is no relation between nodes `a` and `b` 15 | * `1` - Node `b` is a directory child of `a` 16 | * `2` - Node `b` is a file child of `a` 17 | 18 | ## Example 19 | 20 | Input: 21 | 22 | ``` 23 | The directory structure (node indices are present next to each item): 24 | 25 | a #0 26 | b #1 27 | file1.txt #2 28 | c #3 29 | a #0 30 | file2.txt #4 31 | file3.txt #5 32 | 33 | The adjacency matrix: 34 | 35 | 0 1 2 3 4 5 36 | --------------- 37 | 0 | 0 1 0 1 0 2 38 | 1 | 0 0 2 0 0 0 39 | 2 | 0 0 0 0 0 0 40 | 3 | 1 0 0 0 2 0 41 | 4 | 0 0 0 0 0 0 42 | 5 | 0 0 0 0 0 0 43 | ``` 44 | 45 | Output: 46 | 47 | ``` 48 | false # Because `c` is parent of `a` and there is a cycle when traversing the directories. 49 | ``` 50 | -------------------------------------------------------------------------------- /week17/2.Thursday/prereadings/graph.md: -------------------------------------------------------------------------------- 1 | # Graph 2 | 3 | Graphs are used for modeling relations between entities. Be it 4 | connecting cities with streets and highways or representing 5 | friendships between groups of people. Graphs are a powerful 6 | abstraction that removes the details and lets us focus on 7 | the algorithmic problems. We are about to study algorithms 8 | that could be applied on any dataset that could be modeled as 9 | a graph. 10 | -------------------------------------------------------------------------------- /week17/2.Thursday/prereadings/graph_properties.md: -------------------------------------------------------------------------------- 1 | # Graph properties 2 | 3 | Here are some important properties you should know about different 4 | types of graphs. 5 | 6 | ## Vertex 7 | 8 | An entity in the graph. Vertices are a set of items with common properties 9 | that have some sort of relation. 10 | 11 | ## Edge 12 | 13 | Edges express relation between two vertices. If the vertices are connected with 14 | an edge this means that there is relation between them. The relation could 15 | be some custom property. E.g: `are_friends(a, b) => true`, 16 | `are_connected(Sofia, Plovdiv) => false`. 17 | 18 | ## Edge direction 19 | 20 | ### Undirected graph 21 | 22 | A graph which edges have no direction. They could be interpreted as 23 | bidirectional connections. 24 | 25 | 26 | 27 | ### Directed graph 28 | 29 | A graph which edges have a direction. This means that if a node `a` is 30 | related to another node `b` the reverse might not be true. 31 | 32 | 33 | 34 | ## Edge weight 35 | 36 | ### Unweighted graph 37 | 38 | Graphs without edge weights are called unweighted. Edges of unweighted 39 | graphs are considered equals. 40 | 41 | 42 | 43 | ### Weighted graph 44 | 45 | Graphs with edge weights are called weighted. Edges are threated differently 46 | in algorithms with respect to their weights. 47 | 48 | 49 | 50 | ## Number of edges 51 | 52 | ### Simple graph 53 | 54 | Simple graphs allow single edge connecting two vertices. 55 | 56 | 57 | 58 | ### Multigraph 59 | 60 | Multigraphs allow more than one edge to connect two vertices. 61 | 62 | 63 | 64 | ## Cycles 65 | 66 | ### Acyclic graph 67 | 68 | Acyclic graphs are graphs that do not have cycles in paths 69 | between any two vertices. 70 | 71 | 72 | 73 | ### Cyclic graph 74 | 75 | Cyclic graphs are graphs that have at least one cycle in paths 76 | between any two vertices. 77 | 78 | 79 | 80 | ## Connected component 81 | 82 | A subgraph where every any two vertices are connected with a path. 83 | 84 | 85 | -------------------------------------------------------------------------------- /week17/2.Thursday/prereadings/graph_representations.md: -------------------------------------------------------------------------------- 1 | # Graph representations 2 | 3 | Representing graphs in memory is not a problem with a single solution. 4 | Different models allow different operations on the graph to be efficient. 5 | It is crucial to select an appropriate graph representation in order to 6 | be able to use the structure effectively. 7 | 8 | ## Adjacency list 9 | 10 | [Adjacency list](https://en.wikipedia.org/wiki/Adjacency_list) is a 11 | collection of lists each containing the neighbors of a specific vertex 12 | in the graph. This model allows quick access of all neighbors of a 13 | vertex. However, it does not present an efficient way of checking 14 | if two vertices are in relation. 15 | 16 | ## Adjacency matrix 17 | 18 | [Adjacency matrix](https://en.wikipedia.org/wiki/Adjacency_matrix) 19 | is a way of representing a graph using matrix. Vertices of the graph 20 | are labeled with indices that correspond to rows and columns in the 21 | matrix. The value at specific row/column of the matrix could be a 22 | boolean signifying if there is a relation between the two vertices, or 23 | a number used as a weight of the relation. 24 | 25 | Adjacency matrix allows quick check for vertex relations. However, it 26 | requires additional memory quadratic on the number of vertices in the 27 | graph. This memory is wasted if the graph is sparse (there are few 28 | vertex relations). 29 | -------------------------------------------------------------------------------- /week17/2.Thursday/prereadings/graph_traversals.md: -------------------------------------------------------------------------------- 1 | # Graph traversals 2 | 3 | Here we will study different ways of visiting the vertices of a graph following their 4 | relations. This will be useful when we are designing algorithms that work with 5 | the data in the graph and require following a strict pattern when visiting the vertices. 6 | 7 | ## Breadth-First Search 8 | 9 | [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) is a graph traversal 10 | algorithm that explores the neighbor vertices first, before moving to the next level 11 | neighbors. 12 | 13 | 14 | 15 | ## Depth-First Search 16 | 17 | [DFS](https://en.wikipedia.org/wiki/Depth-first_search) is a graph traversal 18 | algorithm that visits all vertices down a branch and then backtracks to neighbors. 19 | 20 | 21 | -------------------------------------------------------------------------------- /week18/1.Tuesday/prereadings.md: -------------------------------------------------------------------------------- 1 | *A HashMap example* 2 | http://www.tutorialspoint.com/java/java_hashmap_class.htm 3 | 4 | *HashMap vs Hashtable vs TreeMap in Java* 5 | http://www.programcreek.com/2013/03/hashmap-vs-treemap-vs-hashtable-vs-linkedhashmap/ 6 | 7 | *Equals and hashcode in java* 8 | http://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java 9 | 10 | *How HashMap works* 11 | http://www.javacodegeeks.com/2014/03/how-hashmap-works-in-java.html 12 | 13 | *Diagram of ALL of java's collections framework:* 14 | http://www.codejava.net/java-core/collections/overview-of-java-collections-framework-api-uml-diagram 15 | -------------------------------------------------------------------------------- /week18/3.Saturday/speaker-notes.md: -------------------------------------------------------------------------------- 1 | Plan 2 | ### 1. Some history 3 | How did the compiling process start? 4 | Java, javac, jar, jarsigner, shell scripts, makes, other tools 5 | #### Age of IDEs? 6 | #### Age of Ant 2000? 7 | - Similiar to which program that you know? 8 | - Ease to begin with (very low learning curve - hence the name) 9 | - Targets, dependencies, 10 | - Examples - it says 'how', not 'what' - tends to be more verbose. 11 | - Based on plugins 12 | - Can actually still do quite a lot - scp, android, ssh, etc 13 | - Dependency management was difficult 14 | ### Maven era 15 | - Dependency management over the network - hooray! 16 | - Very, very rigid structure. Very standartized, concisely defined phases 17 | - Relies on predefined phases, 'goals' 18 | - Extensible via plugins 19 | - Hard to write non-trivial build scripts with lot of intermediate steps - frequently had to write plugins 20 | - Heavy, standartized, rigid XML - tend to become very very big without doing that much out of the ordinary 21 | - Compiling a subset of the classes with maven is... interesting 22 | ### Honorable mention: Ivy 23 | ###### Okay, we got, ant, maven. Why gradle? 24 | 0. Power/flexibility of ant, lifecycle based like maven 25 | 1. Gradle wraps itself and carries itself in the project (unlike maven, nat) 26 | 2. Gradle versioning is intended to be source-controlled 27 | 3. Gradle runs on the Groovy language (e.g. apply plugin: is calling method 'apply' with plugin: java a key-value pair). Unlike ant and maven, NO XML here! 28 | 4. Gradle is the chosen build platform for all new android projects. The previous was 'ant'. 29 | 5. Used for polyglot builds (javascript/java/c++/android and more) - LinkedIn has over 60 languages in their toolchain and ... use gradle 30 | 6. Declarative modeling instead of implementation modelling (writing what you WANT to happen, not HOW) 31 | 7. Compatible with all old Maven/Nexus repos 32 | 8. http://twimgs.com/ddj/images/article/2014/0514/Gradle1.gif 33 | 9. Maven vs gradle codebase comparison http://www.drdobbs.com/jvm/why-build-your-java-projects-with-gradle/240168608 34 | 10. Backed by a professional company, but open source and community driven 35 | 11. Gradle is built... with gradle. You can also install it... with gradle 36 | -------------------------------------------------------------------------------- /week18/3.Saturday/workshop-notes.md: -------------------------------------------------------------------------------- 1 | #### 1. Install gradle 2 | sudo add-apt-repository ppa:cwchien/gradle 3 | sudo apt-get update 4 | sudo apt-get install gradle 5 | 6 | #### 2. Create your first build.gradle file 7 | echo apply plugin: 'java' > build.gradle 8 | gradle build 9 | Examine the resulting tasks and map it to a project build lifecycle! 10 | 11 | #### 3. Reinitialize build file 12 | Delete your build.gradle file 13 | Initialize your java project (with gradle wrapper) 14 | `gradle init --type java-library` 15 | 16 | ### 4. Great, we have a java project. How do we edit this? 17 | But where does the IDE come in? 18 | `apply plugin: 'eclipse'` at the top, 19 | then run `'gradle eclipse'` 20 | Examine now the newly created files (ls -lah) 21 | Try and import the project in Eclipse! 22 | 23 | ### 5. Add dependency to your project - commons lang 24 | compile group: 'org.apache.commons', name:'commons-lang3', version:'3.0' 25 | 26 | ### 6. It does not compile in eclipse? Why? 27 | 28 | ### Run Gradle eclipse 29 | 30 | ### 7. Make 'gradle eclipse' run every time a 'gradle build' is invoked 31 | tasks.getByName("build").dependsOn "eclipse" 32 | 33 | ### Behold - graph configuration API 34 | Java plugin task dependency picture 35 | 36 | ### Create your own task and plug it in! 37 | task hodor << { 38 | 5.times { println "HOLD THE DOOOOR" } 39 | } 40 | 41 | ### Create main method and run your program WITHOUT distributing it 42 | apply plugin: 'application' 43 | mainClassName = 'com.hackbulgaria.com.test.Main' 44 | gradle run 45 | 46 | ### Generate a Fat Jar! 47 | Excercise for the reader : ) 48 | 49 | ### Download mkyong's exmaple https://github.com/mkyong/spring4-mvc-gradle-xml-hello-world 50 | run it via gradle jettyRun 51 | examine the code! 52 | 53 | --------------------------------------------------------------------------------