domingo, 27 de outubro de 2013

MongoDB + Java Course - In progress

MongoDB Course. Home work
=============================

GitHub on
https://github.com/romalopes/hw2-3

- MongoDB Course
Info:
https://education.mongodb.com/courses
Lenght of course: - 7 weeks
Using Maven
to run the project: mvn compile exec:java -Dexec.mainClass=course.BlogController
to test: mvn test
Using Gradle
   to rum the project: gradle run
   to test: gradle test

To create a project with gradle
- copy the directory Gradle to root

1:              - gradle  

2:                  wrapper
3:                      gradle-wrapper.jar
4:                      gradle-wrapper.properties
5:                  ide.gradle
6:          - copy the btch file to root
7:              gradlew (for X)
8:              gradle.bat ( for windows)
9:          - copy settings.gradle to root
10:              Only this inside: rootProject.name = "NAME PROJECT"


- Week 1
- Suports
Based on Json Documents(key, values). It is a document database
In same document Dynamic Schema.  Different collections of data.
- Scalability and performance VS Funcionality
Doesn't support joins and transactions. Documents are hierarchical
- Running
create a directory %MONGO_HOME%\data\db

1:  %MONGO_HOME%/bin/mongo.config  
2:                  ##store data here  
3:                  dbpath=%MONGO_HOME%\data\db  
4:                  ##all output go here  
5:                  logpath=%MONGO_HOME%\log\mongo.log  
6:                  ##log read and write operations  
7:                  diaglog=3  

- Server:
mongod --dbpath data\db
mongod --config %MONGO_HOME%\bin\mongo.config
As a server
mongod --config %MONGO_HOME%\bin\mongo.config --install
net start MongoDB
net stop MongoDB
mongod --remove (remove the service)
- Command line: mongo

Ex:

1:                      mongo test(connects to mongodb already in test collection)  

2:                      use test (switches to test collection)
3:                      show collections
4:                        (collection) (command)
5:                      db.objects.   save({a:1, b:2, c:3})
6:                      db.objects.   save({a:4, b:5, c:6, d:7, e:['a','b']})
7:                      db.objects.find() <- return all documents
8:                      db.objects.find({a:1}) <- Return all documents that have this element
9:                      db.course.hello.save({'name','maths'})
10:                      db.course.hello.find()


- Json
Types of Data
- Array -> list of items -> [...]
- Dictionaries ->associative maps  {key:value} -> {name:"value",city:"value", interests:[ ___, ___, ___]
- Embeded data into documents
If the embeded data exceed 16Mb, because each document should have the maximum of 16Mb
Home Work:
1 - 42
2- 2,3,5
3-366
4- 2805
- Week 2
- CRUD
Create=Insert.  Read=Find.  Update=Update.  Delete=Remove
Does not have a language such as SQL.

1:  - db.people.insert( doc )  
2:              - db.people.find()  
3:              - db.people.findOne({"name": "Anderson"}, {"name":true,"_id":false})  


- all object has a primary key called (_id)
- BSON - Binary JSON Object
- Query
- $gt, $lt,

1:  db.people.findOne({name:{$gt:    "B", $lt:"D"}})  
2:                  db.people.findOne({name:{$gt:    "B"}, {name:{$lt:"D"}} }) --Will return all docs less than D. Ignore the first statement.  


- exists
- To verify if a field exists
- db.people.findOne({name:{ $exists : true}})  -- return all documents that has the field name.
- regex
- db.people.find({name: { $regex : "^A"}}) -> returns everything that starts with A.
ex:db.users.find( {name: {$regex:"q"}, email: {$exists:true} } )
- or //ends with e
- db.people.find( { $or : [ {name: { $regex : "e$" } } , {age : {$exists: true}]})
- db.scores.find( {$or : [ {score : {$lt: 50}}, {score : {$gt: 90}} ]})
- and
- all - return the documents that have all the specified elements in a array
db.accounts.find( { favorites : { $all, [ "a", "b", "c" ] } } )
- in - return all documents that has on of the objects IN a array
db.accounts.find( { name : { $in, [ "Anderson", "Cida"] } } ) -- returns the docs that have Anderson and Cida
- Queries
db.users.find( {email : {work: "romalopes@yahoo.com.br" } } )
or
db.users.find( {email.work: "romalopes@yahoo.com.br" } )
- Cursor


1:                  db.people.insert( {name: "Anderson", email : {work:"111", home:"222"}});  

2:                  db.people.insert( {name: "Cida", email : {work:"111", home:"222"}});
3:                  - cur = db.people.find(); null; //NULL avoid the return.
4:                  - cur.limit(5); null; get only 5 elements.
5:                  - cur.sort( {name: -1 }); null;
6:                  - cur.sort( {name: -1 }).limit(5); null;
7:                  - while(cur.hasNext()) printjson(cur.next());
8:                  - db.scores.find( { type : "exam" } ).sort( { score : -1 } ).skip(50).limit(20)

- count
db.score.count({type:"exam"})
- db.scores.count( {"type":"essay", score: {$gt: 90 } } )
- Update
- db.people.update( { name: "Anderson"} , {name:"Anderson Lopes", address:"114 Hargrave"})
- Creates, remove and replace all the attributes.
- $set
db.people.update( { name: "Anderson"} , {$set: {age:30}} )
- set only the values we want to change.
db.people.update( { name: "Anderson"} , {$inc: {age:3} } )
- increment 3 in age.
- ex:

1:                          db.arrays.insert( {_id:0, a:[1,2,3,4]});  

2:                          db.arrays.update( {_id:0, {$set : {"a.2" : 5 }});
3:                              change the third element from 3 to 5.
4:                          db.arrays.update( {_id:0, {$push : {a : 6 }});
5:                              add at the end of array
6:                          db.arrays.update( {_id:0, {$pop : {a : 1 }}); //remove the last element
7:                          db.arrays.update( {_id:0, {$pop : {a : -1 }}); //remove the first element
8:                          db.arrays.update( {_id:0, {$pushAll : {a : [6, 7, 8, 9 }});
9:                          db.arrays.update( {_id:0, {$pull : {a : 3} }); //remove the element that the value is 3
10:                          db.arrays.update( {_id:0, {$pullAll : {a : [6, 7, 8, 9 }}); // remove all elements with the values in the second array


- $unset (remove a field from a collection)
db.people.update( { name: "Anderson"} , {$unset: {age:1} } )
- Multi-update
Update multiple documents
db.people.update( {} , {$set :{"title": "Dr" } }, {multi: true} );
db.scores.update ( { score: {$lt:70} }, {$inc: {score:20}}, {multi:true});
- Remove a database

1:                  use DATABASE  

2:                  db.dropDatabase()

- remove

1:                  db.people.remove() //remove everything from the collection.  

2:                  db.people.drop() //faster than remove
3:                  db.people.remove( {name:"Alice"})
4:                  db.people.remove( {name: {$gt: "M" }} )
5:                  db.scores.remove( {score: { $lt: 60 }})
6:              - db.runCommand( {getLastError:1})

return the last result of a command.  It can be a error, a result of a update and so on.
With Java
CRUD


1:                  INSERT DBOBject(interface) . BasicDBObject with is a LinkedHashMap<String, Object>  

2:                   BasicDBObject doc = new BasicDBObject();
3:                      doc.put("userName", "anderson");
4:                      doc.put("birthDate", new Date(2344242));
5:                      doc.put("programmer", true);
6:                      doc.put("age", 8);
7:                      doc.put("languages", Arrays.asList("Java", "C++"));
8:                      doc.put("address", new BasicDBObject("street", "114 Hargrave")
9:                                  .append("town", "Paddington")
10:                                  .append("zipCode", 2021));
11:                      { "_id" : "user1",
12:                        "interests" : [ "basketball", "drumming"]    }
13:                      new BasicDBObject("_id", "user1").append("interests", Arrays.asList("basketball", "drumming"));

FIND


1:                  DB courseDB = client.getDB("course");  

2:                      DBCollection collection = courseDB.getCollection("findCriteriaTest");
3:                      collection.drop();
4:                      for(int i=0; i<10; i++) {
5:                          collection.insert(new BasicDBObject( "x", new Random().nextInt(2)).
6:                                                            append("y", new Random().nextInt(100)));
7:                      }
8:                      System.out.println("\n Find All");
9:                      DBCursor cursor1 = collection.find();
10:                      try {
11:                          while(cursor1.hasNext()) {
12:                              DBObject all = cursor1.next();
13:                              System.out.println(all);
14:                        }
15:                      } finally {
16:                          cursor1.close();
17:                      }
18:                      DBObject query = new BasicDBObject("x", 0)
19:                                                                          //AND in Y
20:                                      .append("y", new BasicDBObject("$gt", 10).append("$lt", 90));
21:      //OR
22:                      QueryBuilder builder = QueryBuilder.start("x").is(0)
23:                              .and("y").greaterThan(10).lessThan(90);
24:                      System.out.println("\n Count");
25:                      long count = collection.count(query); // builder.get()
26:                      System.out.println(count);
27:                      System.out.println("Find One");
28:                      DBObject one = collection.findOne(query); //builder.get()
29:                      System.out.println(one);
30:                      System.out.println("\n Find All");
31:                      DBCursor cursor = collection.find(query); //builder.get()
32:                      try {
33:                          while(cursor.hasNext()) {
34:                              DBObject all = cursor.next();
35:                              System.out.println(all);
36:                          }
37:                      } finally {
38:                          cursor.close();
39:                      }
40:                      for(int i=0; i<10; i++) {
41:                          collection.insert(new BasicDBObject( "_id", i).
42:                append("start",
43:                    new BasicDBObject("x", new Random().nextInt(90) + 10)
44:                          .append("z", new Random().nextInt(90) + 10)
45:                ).append("end",
46:                  new BasicDBObject("x", new Random().nextInt(90) + 10)
47:                      .append("z", new Random().nextInt(90) + 10)
48:                  )
49:                          );
50:                      }
51:                      //QueryBuilder builder = QueryBuilder.start("start.x").greaterThan(50);
52:                      //DBCursor cursor = collection.find(builder.get(),
53:                      //    new BasicDBObject("start.x", true).append("_id", false).append("end.z", true));
54:                      DBCursor cursor = collection.find()
55:                                  .sort(new BasicDBObject("_id", -1)).skip(5).limit(3);
56:                      DBCursor cursor = collection.find()
57:                                  .sort(new BasicDBObject("start.x", -1).append("end.z",1)).skip(5).limit(3);

UPDATE
REMOVE

1:                                                  //query  
2:                      collection.update(new BasicDBObject("_id", "alice"),  
3:                              new BasicDBObject("age", 35));//update  
4:                      collection.update(new BasicDBObject("_id", "alice"),  
5:                              new BasicDBObject("gender", "Female"));//update  
6:                      //will remove the gender - Female and insert the Title Srs  
7:                      collection.update(new BasicDBObject("_id", "alice"),  
8:                              new BasicDBObject("$set" , new BasicDBObject("Title", "Srs")));//update  
9:                      //To insert, it is needed two last parameters  
10:                      collection.update(new BasicDBObject("_id", "frank"),         //to insert  
11:                              new BasicDBObject("$set" , new BasicDBObject("Title", "Sr")), true, false);//update  
12:                      collection.update(new BasicDBObject(),//every document        //to update  
13:                              new BasicDBObject("$set" , new BasicDBObject("Graduation", "Masters")), false, true);//update  
14:                      //collection.remove(new BasicDBObject());  
15:                      collection.remove(new BasicDBObject("_id", "alice"));  


- About blog
View - ftl - freemarker
controller/model java/spark.

- Home Work -
1 - db.grades.find({score:{$gte:65}}).sort( { score : 1 } ).limit(1)
2 - 124
3 - fhj837hf9376hgf93hf832jf9
- Week 3
- MongoDB Schema Design
Application-Driven Schema
. Features
Rich Documents
Pre join data for fast access
No Joing
No Constraina like MySql
Atomic operations(no transactions)
No Declared Schema

A Simple project in Grails - Portugues, LivroVisitas


Criação de um projeto/ Livro de Visitas usando Grails



Code in github/romalopes/livrovisitas

-- Criação do projeto


1:  create-project livrovisitas  



-- Criação do Controller inicial


1:  create-controller br.com.k2sistemas.Controle  

------------------------------------------------------------------
-- Implementação do Controller


1:  //ControleController.groovy  
2:  class ControleController {  
3:    def index() {   
4:          render "<h1>Inicio!</h1>"  
5:      }  
6:      def ola = {  
7:          render "<h1>Olá Pessoal da K2!</h1>"  
8:      }  
9:      def acao = {  
10:          [par1: "Hello", par2: "World!", date: new Date()]  
11:      }  
12:  }  
------------------------------------------------------------------
-- GSP chamada pelo ControlleController.acao


1:  <!-- acao.gsp -->  
2:  <!-- grails-app/views/controle -->  
3:  <html>  
4:      <body>  
5:          <p>${par1} ${par2} na data ${date}</p>  
6:      </body>  
7:  </html>  

------------------------------------------------------------------
-- Criação das classes de domínio


1:  create-domain-class br.com.k2sistemas.livroVisitas.User  
2:  create-domain-class br.com.k2sistemas.livroVisitas.Feedback  
3:  create-domain-class br.com.k2sistemas.livroVisitas.Comment  

------------------------------------------------------------------

-- Implementação das classes de domínio


1:  package br.com.k2sistemas.livroVisitas  
2:  class Feedback {  
3:   String title  
4:   String feedback  
5:   Date dateCreated // Nome predefinido pelo Grails a ser preenchido automaticamente  
6:   Date lastUpdated // Nome predefinido pelo Grails a ser preenchido automaticamente  
7:   // Relacionamento com outras classes  
8:   User user  
9:   static hasMany=[comments:Comment]  
10:   // Contrains definidas como static   
11:    static constraints = {  
12:          title(blank:false, nullable: false, size:3..80)  
13:          feedback(blank:false, nullable:false,size:3..500)  
14:          user(nullable:false)  
15:    }  
16:      String toString(){  
17:          return title;  
18:       }  
19:  }  

------------------------------------------------------------------

-- Implementação das classes de domínio


1:  package br.com.k2sistemas.livroVisitas  
2:  class User {  
3:   String name  
4:   String email  
5:   String webpage  
6:    static constraints = {  
7:          name (blank:false, nullable:false, size:3..30, matches:"[a-zA-Z1-9_]+")   
8:          email (email:true)  
9:          webpage (url:true)  
10:    }  
11:   String toString(){  
12:    return name;   
13:   }  
14:  }   
------------------------------------------------------------------

-- Implementação das classes de domínio


1:  package br.com.k2sistemas.livroVisitas  
2:  class Comment {  
3:   String comment  
4:   Date dateCreated // Nome predefinido pelo Grails a ser preenchido automaticamente  
5:   Date lastUpdated // Nome predefinido pelo Grails a ser preenchido automaticamente  
6:   User user;  
7:   // Garante que o Comment de um feedback será deletado caso o feedback seja deletado. Cascade  
8:   static belongsTo=[feedback:Feedback]  
9:    static constraints = {  
10:          comment (blank:false, nullable: false, size:5..500)  
11:          user (nullable: true) // Comments são permitidos sem User  
12:    }  
13:   String toString(){  
14:    if (comment.size()>20){  
15:     return comment.substring(0,19);  
16:    } else   
17:          return comment;   
18:     }  
19:  }   

-----------------------------------------

-- Criação dos controllers relativos às classes de domínio


1:  generate-controller br.com.k2sistemas.livroVisitas.Feedback   
2:  generate-controller br.com.k2sistemas.livroVisitas.User   
3:  generate-controller br.com.k2sistemas.livroVisitas.Comment  

-----------------------------------------

-- Scarffold stático. Modificar as classes de controle

1:   // Only change here  
2:   def scaffold = true   


-----------------------------------------

-- Criação das Views, com scaffold = false

1:  generate-views br.com.k2sistemas.livroVisitas.Feedback   
2:  generate-views br.com.k2sistemas.livroVisitas.User   
3:  generate-views br.com.k2sistemas.livroVisitas.Comment  

-----------------------------------------

-- Controllers e Views Poderiam ser geradas assim.

1:  generate-all  


-----------------------------------------

-- Mudar o DataSource para update.

-----------------------------------------

-- Autenticação

1:  create-filters security  

Create the SecurityFilters

1:  class SecurityFilters {  
2:    def filters = {  
3:      loginCheck(controller: '*', action: '*') {  
4:        before = {  
5:          if (!session.user && actionName != "login") {  
6:                redirect( controller: "controle", action: "login")  
7:            return false  
8:          }  
9:        }  
10:      }  
11:    }  
12:  }  


1:  <%--/controle/login.gsp --%>  
2:  <html>  
3:    <body>  
4:      <div class="body">  
5:        <h1>Login</h1>  
6:        <div class="message"><h3>${message}</h3></div>  
7:        <g:form action="login" method="post" >  
8:          <div class="dialog">  
9:            <table>  
10:              <tbody>  
11:                <tr class="prop">  
12:                  <td valign="top" class="name">  
13:                   <g:message code="message" default="Nome do Usuário:" />  
14:                  </td>  
15:                  <td valign="top" class="value">  
16:                    <g:textField name="username" value="${username}" />  
17:                  </td>  
18:                </tr>  
19:                <tr>  
20:                  <td>  
21:                   <g:message code="message" default="Senha: " />  
22:                  </td>  
23:                  <td valign="top" class="value ">  
24:                    <g:passwordField name="password" />  
25:                  </td>  
26:                </tr>  
27:              </tbody>  
28:            </table>  
29:          </div>  
30:          <div class="buttons">  
31:            <span class="button"><g:actionSubmit action="login" value="logado" /></span>  
32:          </div>  
33:        </g:form>  
34:      </div>  
35:    </body>  
36:  </html>  


No controleController

1:      def login() {  
2:          if(!params.username)  
3:          {  
4:              render(view: "login")  
5:              return  
6:          }  
7:          //AQUI INCLUIR TODAS AS REGRAS DE AUTENTICAÇÃO  
8:          def user = User.findByName(params.username)  
9:          if (user) {  
10:              session.user = params.username  
11:              render(view: "/index")  
12:          } else {  
13:              render(view: "login", model: [message: "Usuario ${params.username} nao encontrado"])  
14:          }  
15:      }  
16:      def logout () {  
17:          session.invalidate()  
18:          render(view: "login")  
19:      }  

UrlMappings.groovy

1:  "/"(controller: 'controle', action: 'index')  


-----------------------------------------

BootStrap


1:  class BootStrap {  
2:      def init = { servletContext ->  
3:           User user = new User(name:'anderson', email:'romalopes@romalopes.com.br', webpage:'http://www.romalopes.com.br')  
4:           if (!user.save()){  
5:               log.error "Could not save user!!"  
6:               log.error "${user.errors}"  
7:           }  
8:   }  
9:       def destroy = {  
10:       }  
11:  }  

--------------------------------------
-- Conversão e renderização de outros formatos. Inserir no ControleController.groovy

1:      def xmlList = {  
2:          render Feedback.list() as XML  
3:       }  


--------------------------------------

-- Utilização de Plugin


1:      install-plugin searchable  

-- Em cada classe de domínio que se deseja usar o searchable

1:    static searchable = true     


--------------------------------------

-- teste

1:  test-app  

--------------------------------------
-- Criação do War


1:  war  

Basics of Gradle based on User Guide

Gradle - http://www.gradle.org/docs/current/userguide/userguide_single.html#overview
Introduction
- Build Automate, test, publishing, deployiment and so on.
- Combines the flexibility of ANT with dependency management and conventions of Maven.
- Uses Groovy DSL and uses a declarative way to describe the builds.
Features
Declarative builds and build-by-convention
Gradle uses DSL(Domain Specific Language) based on Groovy.
Language for dependency based programming
The tasks are based in a hierarchy, favoring the builds
Structure your build
Easy to compose buid from reusable pieces
Deep API
Allow to monitor and customize the configuration and behavior execution
Scalability
Reusability allows one project uses parts of other projects increasing the produtivity
Multi-project builds
You can rebuild a project or its sub-project, that depends on another sub-project.
Different ways to manage dependencies
Maven has just one way. Can integrate with maven and ivy, or just use jars or directories.
Groovy
Insteady of XML.

Simple examples
- Project
Each project has many tasks
- To create a simple project, create a file build.gradle
Ex:

1:  task hello {  
2:  doLast {  
3:  println 'Hello world!'  
4:  }  
5:  }  
6:  OR  
7:  task hello << {  
8:                      println 'Hello world!'  
9:                  }  
RUN: gradle -q hello
It is possible to add behavior to an existing task

1:          task hello << {  
2:              println 'Hello Earth'  
3:          }  
4:          hello.doFirst {  
5:              println 'Hello Venus'  
6:          }  

Task Dependencies
One task can depend on another using:


1:  task taskX(dependsOn: 'taskY') << {  

Dynamic Tasks
Tasks can be dynamic. In this case, 4 tasks are created (task0 to task3). There is a dependency.

1:          4.times { counter ->  
2:  task "task$counter" << {  
3:                  println "I'm task number $counter"  
4:              }  
5:          }  
6:          task0.dependsOn task2, task3  
Default Tasks

1:  defaultTasks 'task1', 'task2'  
- Plugins
Plugin is an extension to Grails which configures a project in some way, typically adding pre-configured tasks.
Gradle with Java plugin
apply plugin: 'java'
To create a project, it is good to have the same structure that MAVEN project
PROJECT
- src
main
- java
- test
- java
- resources
- resources
buid
libs
Main Commands
gradle -->
build -> compile, test, build jar
clean -> delete the build directory
assemble -> Compile and build the jar. Does not run the tests
check -> compile and test
External dependencies
Repositories

1:  repositories {  
2:    mavenCentral()  
3:  }  
Dependencies

1:  dependencies {  
2:  compile -> dependency in compile-time  
3:  testCompile -> dependency in compile-time for test  
4:  runtime -> dependency in runtime  
5:  }  


Multi-project Java build create a file called: settings.gradle in the same directory of build.gradle.
Ex:

1:       include "shared", "api", "services:webservice", "services:shared"  
2:       rootProject.children.each { prj -> //para cada filho  
3:            prj.projectDir = new File("$rootDir/subprojects/$prj.name")  
4:       }  
5:       rootProject.name = 'groovy' // set the name of rootProject.  

Basics of Maven

- Maven
                Features and goals:
                               - Simplify the build process, sharing JARs, publishing informations in a easy way.
                               - Deploy a system
                               - Manage Documentation, dependencies, releases, distribution, report
                               - Maven works on top of ANT
                                               Ant needs you to write the logic and provide de data
                                               Maven needs you to provide the data and know how to do most things.
                               - Maven has a local repository and well named jars, docs, etc.
                                               Provide a single location for downloads which versions are created automatically
                - POM (Project Object Model)
                              
                - Create a Project
                               Simple way:
                                                - mvn archetype:generate
                                                - There are over 850 archetypes.  Use the 314(
                                                -archetype-quickstart), sugested but maven
                                                - Version of maven-archetype-quickstart: Use the sugested(1.1), number 6.
                                                - groupId: The groupId that will be inside the pom.xml. I use: br.com.romalopes.meven2Test
                                                - artifactId: mavenToGradle.  The project will be created inside this directory.
                                                - Version: Accept the sugested.
                                                - Value for property papckage: The package that will be create inside the structure:br.com.romalopes.meven2Test
                                                - Confirm
                              
                               - A more sofisticated way
                                               - mvn archetype:generate -DgroupId=br.com.romalopes.maven2Test -DartifactId=maven-test -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
                It creates a structure like that:
                - my-app
                               |-- pom.xml
                               -- src
                                               |-- main
                                               |   `-- java.
                                               |       `-- com.
                                               |           `-- mycompany-
                                               |               `-- app
                                               |                   `-- App.java
                                               |-- resources
                                                              -- META-INF
                                                              -- application.properties   -->  InputStream is = getClass().getResourceAsStream( "/test.properties" );
                                               -- test
                                                               -- java
                                                                               -- com
                                                                                              -- mycompany
                                                                                                              -- app
                                                                                                                              -- AppTest.java
                - Phases to buil a project
                               Validate
                               generate-sources
                               process-sources
                               generate-resources
                               process-resources
                               compile
                               mvn package
                               integration-test
                               verify
                               install - install into the local repository
                               deploy - copies the final package to the remote repository
                               - others
                                               clean
                                               test
                                               dependency:copy-dependencies
                                               mvn site - generate a site for project documentation
                                               can call
                                                               mvn clean dependency:copy-dependencies package
                              
                - maven to Eclipse
                               Simple java
                                               mvn eclipse:eclipse
                               Dynamic Web Project
                                               mvn eclipse:eclipse -Dwtpversion=1.5
                                               In Eclipse:
                                                               Properties->Modify Project->Change Facet
                - plugins
                               To customize the build for a Maven Project
                                               
- Example

1:          <project xmlns="http://maven.apache.org/POM/4.0.0"  
2:           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
3:           xsi:schemaLocation="http://maven.apache.org/POM/4.0.0  
4:                               http://maven.apache.org/xsd/maven-4.0.0.xsd">  
5:           <modelVersion>4.0.0</modelVersion>  
6:           <groupId>com.mycompany.app</groupId>  
7:           <artifactId>my-app</artifactId>  
8:           <version>1.0-SNAPSHOT</version>  
9:           <packaging>jar</packaging>  
10:           <name>Maven Quick Start Archetype</name>  
11:           <url>http://maven.apache.org</url>  
12:           <dependencies>  
13:              <dependency>  
14:               <groupId>junit</groupId>  
15:               <artifactId>junit</artifactId>  
16:               <version>3.8.1</version>  
17:               <scope>test</scope>  
18:              </dependency>  
19:           </dependencies>  
20:           <build>  
21:              <resources>  
22:               <resource>  
23:                  <directory>src/main/resources</directory>  
24:                  <filtering>true</filtering>  
25:               </resource>  
26:              </resources>  
27:           </build>  
28:           <properties>  
29:              <my.filter.value>hello</my.filter.value>  
30:           </properties>  
31:          </project>      

Data Structures


- Hash Table
Combinam uma tabela a uma função. Particiona o conjunto de dados a fim de facilitar a busca.
Aloca nos buckets
Vetor de vetores dinâmicos. Função matemática elaborada, ex: F(x) = x%10
Dispersão quando um buckets fica mais cheio. 16 bytes MD5, SHA-1

- Grafo
Grafo G consiste de um conjunto finito de elementos chamado vértice e um conjunto de pares não ordenados de vértices chamado arestas.
- algoritmo de bellman-ford
- Arvore
Binária
Raiz tem até dois filhos.
B
Raiz tem de 2 até N+1 filhos.
Nós interno tem [N/2]
Filhs [N/2]-1, N-1
Folhas sempre no mesmo nível
Ao remover
Redistribuição
Se os irmãos tiverem mais que o mínimo
Concatenação
Se os irmãos tiverem o mínimo
Ao remover o não folha, vai jogando pra baixo até virar folha.
Arvore Balanceada AVL
Se para cada nós as sub-arvores a direita ou esquerda tiverem a mesma altura ou de 1.
Fator de balanceamento(-1, 0 ou 1)
Se fator + rotação à esquerda
Se fator - rotação à direita
Arvore T
Baseada na AVL sendo binária e auto-balanceada.
Da B por ter estrutura de índice.
Balenaceamento como na AVL, mas com menos frequencia pq dados se movimento no nó.
Red-Black Tree
Tipo especial de arvore binária.
O nó raíz é negro.
Um nó vermelho só pode ter filhos negros. Nós inserido é sempre vermelho.
Todos os caminho a partir da raíz tem o mesmo número de nós pretos.
Splay tree
Itens mais acessados são movidos pra cima.
- Coloração de gráfico (coloring algorithm)
Para cada vértice, percorrer os seus vizinhos e colorí-los.
Escolher o nó com maior número de ligações.
- Minimax
Minimax for next move
Assume o oponente força vc a ir no pior caminho.
Maximizo a minha jogada e minimizo a adversário
- Alfta-Beta
Começa como o MinMax. Não expande a nós irrelevantes, pois faz a poda.
Na recursão pergunta se tem algum antecessor com valor "ctrário" maior ou menor.
Ex, se eu tive no MIN, pergunta se tem algum ancestral MAX maior que o elemento?
Se tiver no MAX, existe algum ancestral MIN menor que o elemento?

List of some Sort Methods


- Método de ordenação
BUBBLE
Um loop eterno. Vai trocando até acaber.
Funciona como uma bolha
Ordem N2
INSERTION
for dentro de for. No segundo for, parte do elemento definido no for anterior e vai voltando até o início tentando trocar.
N2.
//Algorithm
1:  for(j = 1; j < length; j++) // Note!  
2:          {  
3:              keyelement = array[j];  
4:              for (i = j - 1; (i >= 0) && (array[i] < keyelement); i--)  
5:              {  
6:                  array[i+1] = array[i];  
7:              }  
8:              array[i+1] = keyelement;  
9:          }  
SELECTION
for dentro de for, em cada passada, escolhe o menor e troca no final do loop

//Algorithm

1:      for (i= length - 1; i > 0; i--)  
2:      {  
3:        firstelement = 0;  
4:        for (j=1; j<=i; j++)  
5:        {  
6:           if (array[j] < array[firstelement])  
7:           firstelement = j;  
8:        }  
9:        temp = array[firstelement];  
10:        array[firstelement] = array[i];  
11:        array[i] = temp;  
12:          }  
SHELL
Generaliza o insert sort. Permite que itemns longe sejam trocado.
Começa com ordenamentos entre elementos em distancia = N/2 .
Enquanto tiver troca continua.
Depois faz o mesmo para o distancia = distancia/2.
Repete até distancia < 1; //Algorithm
1:              d = length;  
2:              flag = 1;  
3:              while ( flag || (d > 1))  
4:              {  
5:                  flag = 0;  
6:                  d = (d + 1)/2;  
7:                  for (i =0; i < (length - d); i++)  
8:                  {  
9:                      if (array[i + d] > array[i])  
10:                      {  
11:                          tmp = array[i+d];  
12:                          array[i + d] = array[i];  
13:                          array[i] = tmp;  
14:                          flag = 1;  
15:                      }  
16:                  }  
17:              }  
MERGE - NlogN
Algorithm of Divide and conquer. Lista dividida em 2, depois essa é dividida em dois.
Faz o mesmo para a direita e pra esquerda. Depois faz o merge.
No merge criar um helper com os valores do vetor e tem-se low, middle e high. Percorre-se enquanto i<=middle e j<=high. Se o valor o i < valor do helper[j], copia v[i] e i++, senão v[j] e j++. Copia o resto do do helper para o v
1:           private void mergesort(int low, int high) {  
2:              // Check if low is smaller then high, if not then the array is sorted  
3:              if (low < high) {  
4:               // Get the index of the element which is in the middle  
5:               int middle = low + (high - low) / 2;  
6:               // Sort the left side of the array  
7:               mergesort(low, middle);  
8:               // Sort the right side of the array  
9:               mergesort(middle + 1, high);  
10:               // Combine them both  
11:               merge(low, middle, high);  
12:              }  
13:           }  
14:        private void merge(int low, int middle, int high) {  
15:              // Copy both parts into the helper array  
16:              for (int i = low; i <= high; i++) {  
17:               helper[i] = numbers[i];  
18:              }  
19:              int i = low;  
20:              int j = middle + 1;  
21:              int k = low;  
22:              // Copy the smallest values from either the left or the right side back  
23:              // to the original array  
24:              while (i <= middle && j <= high) {  
25:               if (helper[i] <= helper[j]) {  
26:                  numbers[k] = helper[i];  
27:                  i++;  
28:               } else {  
29:                  numbers[k] = helper[j];  
30:                  j++;  
31:               }  
32:               k++;  
33:              }  
34:              // Copy the rest of the left side of the array into the target array  
35:              while (i <= middle) {  
36:               numbers[k] = helper[i];  
37:               k++;  
38:               i++;  
39:              }  
40:       }  

QUICK SORT
http://www.youtube.com/watch?v=gu7x-jgzuOU
Método de dividir e conquistar. Escolhe o pivo e ordena de acordo com ele.
escolhe um pivot, no N/2.
Depois divide em duas listas. E joga os maiores a direita do pivo e os menores a esquerda através das trocas sucessivas.
i=low, j=high. Faz o mesmo à direita e a esquerda.

1:               private void quicksort(int low, int high) {  
2:                  int i = low, j = high;  
3:                  // Get the pivot element from the middle of the list  
4:                  int pivot = numbers[low + (high-low)/2];  
5:                  // Divide into two lists  
6:                  while (i <= j) {  
7:                   // If the current value from the left list is smaller then the pivot  
8:                   // element then get the next element from the left list  
9:                   while (numbers[i] < pivot) {  
10:                      i++;  
11:                   }  
12:                   // If the current value from the right list is larger then the pivot  
13:                   // element then get the next element from the right list  
14:                   while (numbers[j] > pivot) {  
15:                      j--;  
16:                   }  
17:                   // If we have found a values in the left list which is larger then  
18:                   // the pivot element and if we have found a value in the right list  
19:                   // which is smaller then the pivot element then we exchange the  
20:                   // values.  
21:                   // As we are done we can increase i and j  
22:                   if (i <= j) {  
23:                      exchange(i, j);  
24:                      i++;  
25:                      j--;  
26:                   }  
27:                  }  
28:                  // Recursion  
29:                  if (low < j)  
30:                   quicksort(low, j);  
31:                  if (i < high)  
32:                   quicksort(i, high);  
33:               }  


HEAP (nLogn) com pior = caso médio
Cria-se uma arvore heap na ordem da lista que vira uma árvore balanceada.
Ordena: Troca os valores das sub-arvores com os elementos acima, caso o valor seja maior recursivamente até chegar à raiz.
Envia esse valor pro vetor. Como a raiz ficará vazia, pegue qualquer elemento folha e jogue pra raíz.
A ideia é dos menores valores irem sendo jogados para a raiz.
http://sciencetechpedia.blogspot.com.au/2012/11/heap-sort-using-java.html

JQuery - Summary

Jquery
Syntax and First Example
 $(selector).action()  
 $(document).ready(function(){  
 $("p").click(function(){  
 $(this).hide();  
 });  
 });  

Import:
      <head>  
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">  
      </head>  

Selectors:
      $(this).css("background-color","#cccccc"); - hides the current element.  
      $("p").hide() - hides all <p> elements.  
      $(".test").hide() - hides all elements with class="test".  
      $("#test").hide() - hides the element with id="test".  
      $("p.intro")     Selects all <p> elements with class="intro"  
      $("tr:even")     Selects all even <tr> elements  

Events:
Mouse Events Keyboard Events Form Events Document/Window Events
click keypress submit load
dblclick keydown change resize
mouseenter keyup focus scroll
mouseleave blur unload

Efects:
animate() Runs a custom animation on the selected elements
clearQueue() Removes all remaining queued functions from the selected elements
delay() Sets a delay for all queued functions on the selected elements
dequeue() Removes the next function from the queue, and then executes the function
fadeIn() Fades in the selected elements
fadeOut() Fades out the selected elements
fadeTo() Fades in/out the selected elements to a given opacity
fadeToggle() Toggles between the fadeIn() and fadeOut() methods
finish() Stops, removes and completes all queued animations for the selected elements
hide() Hides the selected elements
queue() Shows the queued functions on the selected elements
show() Shows the selected elements
slideDown() Slides-down (shows) the selected elements
slideToggle() Toggles between the slideUp() and slideDown() methods
slideUp() Slides-up (hides) the selected elements
stop() Stops the currently running animation for the selected elements
toggle()

Ex:
 <script>   
           $(document).ready(function(){  
            $("#start").click(function(){  
                $("div").animate({height:300},3000);  $("div").animate({width:300},3000);  
            });  
           });  
           </script> </head> <body>  
           <p> <button id="start">Start Animation</button>  
           <button id="complete">Finish Current Animation</button>  
           </p>  
           <div style="background:#98bf21;height:100px;width:100px">  
           </div>  
           </body>  
           <script>  
           $(document).ready(function(){  
            $("#button1").click(function(){  
                var div = $("#div1");  
                div.animate({height:300},"slow"); div.animate({width:300},"slow"); div.animate({height:100},"slow"); div.animate({width:100},"slow");  
                $("span").text(div.queue().length);    
                $("#div1").fadeToggle();  $("#div2").fadeToggle("slow");   $("#div3").fadeToggle(3000);  
            });  
            $("#button2").click(function(){  $("p").fadeTo(1000,0.4); });  
            $("#button3").click(function(){  $("#div1").finish(); });  
            $("#button4").click(function(){  $("#div1").stop(); });  
           });  
           </script>  
           </head>  
           <body>  
           <p>The queue length is: <span></span></p>  
           <button id="button1">fade in/out</button> <button id="button2">fade to boxes</button>   
           <button id="button3">Complete</button> <button id="button4">Stop</button>  
           <br><br> <div id="div1" style="width:80px;height:80px;background-color:red;"></div>  
           <br> <div id="div2" style="width:80px;height:80px;background-color:green;"></div>  
           <br> <div id="div3" style="width:80px;height:80px;background-color:blue;"></div>  
           </body>  



HTML content:
text(), html(), and val()
 <script>  
           $(document).ready(function(){  
            $("#button1").click(function(){ alert("Value: " + $("#testVal").val()); $("#testVal").val("Dolly Duck"); });  
            $("#button2").click(function(){ $("#testAttrb").attr( "width", "200px");  alert("Width of div: " + $("#testAttrb").width());  $("#testAttrb").width("500px") });  
            $("#button3").click(function(){ alert("Text: " + $("#testTextHtml").text());  $("#testTextHtml").text("Hello world!"); $("#testTextHtml").after("Some text after");});   
            $("#button4").click(function(){ alert("HTML: " + $("#testTextHtml").html()); $("#testTextHtml").html("<b>Hello world!</b>"); });  
           });  
           </script> </head> <body>  
           <p>Name: <input type="text" id="testVal" value="Mickey Mouse"></p>  
           <div id="testAttrb" style="height:100px;width:300px;padding:10px;margin:3px;border:1px solid blue;background-color:lightblue;"></div><br>  
           <p id="testTextHtml">This is some <b>bold</b> text in a paragraph.</p>  
           <button id="button1">Val</button> <button id="button2">Attr</button> <button id="button3">Text</button> <button id="button4">Html</button>  
           </body>  


HTML Remove
           <script>  
           $(document).ready(function(){  
            $("button").click(function(){  
                $("p").remove(".italic"); $("#div1").empty();  
            });  
           });  
           </script> </head> <body>  
           <div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">This is some text in the div. </div>  
           <p class="italic"><i>This is another paragraph in the div.</i></p>  
           <button>Remove </button>  
           </body>  

Manipulating CSS
 addClass() - Adds one or more classes to the selected elements  
                $("#div1").addClass("important blue");  
                .important {  
                     font-weight:bold;     font-size:xx-large;  
                }  
                .blue { color:blue; }  
                <div id="div1">This is some important text!</div>  

removeClass() - Removes one or more classes from the selected elements
      $("h1,h2,p").removeClass("blue");  
           toggleClass() - Toggles between adding/removing classes from the selected elements  
                $("h1,h2,p").toggleClass("blue");  
           css() - Sets or returns the style attribute  
            $("button").click(function(){  
                alert("Background color = " + $("p").css("background-color"));  
                $("p").css("background-color","yellow");  
            });  
            <p style="background-color:#ff0000">This is a paragraph.</p>  
Dimentions
 var txt="";  
           txt+="Width of div: " + $("#div1").width() + "</br>"; method sets or returns the width of an element (includes NO padding, border, or margin).  
           txt+="Height of div: " + $("#div1").height() + "</br>"; innerHeight() -   
           txt+="Inner width of div: " + $("#div1").innerWidth() + "</br>"; method returns the width of an element (includes padding).  
           txt+="Inner height of div: " + $("#div1").innerHeight() + "</br>";  
           txt+="Outer width: " + $("#div1").outerWidth() + "</br>"; method returns the width of an element (includes padding and border).  
           txt+="Outer height: " + $("#div1").outerHeight();  
           $("#div1").html(txt);  
Transversing Ancestors / Descendant / Sideways
 $("span").parent();  
           $("span").parents();  
           $("span").parents("ul");  
           $("span").parentsUntil("div");  
           $("div").children();  
           $("h2").siblings();  
            $("h2").siblings("p"); //sibilings of h2 which are p  
           $("h2").next(); //Next sibiling // prev()  
           $("h2").nextAll(); //All next sibilings // prevAll()  
            $("h2").nextUntil("h6"); //next sibilings of h2 until h6 //prevUntil()  
           $("div p").first(); //first p inside div  
           $("p").not(".intro").css("background-color","yellow"); // Every p expect those which are class .intro. Opposite to filter and eq(index)  

AJAX
 Load  
                $("#div1").load("demo_test.txt");  
           Get  
                $("button").click(function(){  
                     $.get("demo_test.asp",function(data,status){  
                          alert("Data: " + data + "\nStatus: " + status);  
                     });  
                });  
           Post  
                $("button").click(function(){  
                     $.post("demo_test_post.asp",  
                     {  
                          name:"Donald Duck",  
                          city:"Duckburg"  
                     },  
                     function(data,status){  
                          alert("Data: " + data + "\nStatus: " + status);  
                     });  
                });