SlideShare uma empresa Scribd logo
1 de 22
Finding Clojure




Kurt Harriger     @kurtharriger
The Challenge

Twitter search url filter
Project Folder
% lein new twitturl
Created new project in: /Users/kurtharriger/code/twitturl




├──   README
├──   project.clj
├──   src
│     └── twitturl
│          └── core.clj
└──   test
      └── twitturl
           └── test
               └── core.clj

 % git init && git add -A && git commit -m “create project”
project.clj
(defproject twitturl "1.0.0-SNAPSHOT"
  :description "Twitturl aggregator"
  :dependencies [[org.clojure/clojure "1.2.0"]
         [org.clojure/clojure-contrib "1.2.0"]
         [ring "0.3.7"]
         [clj-http "0.1.2"]]
  :dev-dependencies [[lein-ring "0.4.0"]]
  :ring {:handler twitturl.core/app})
Appleholics
% brew install leiningen


       Non Appleholics
Find Leiningen for Clojure on
https://github.com/technomancy/leiningen
% lein self-install
S-Expressions
 Clojure:
 (defn fn [arg1 & more] arg1)


defn is a macro used here with 3 parameters:
function name, arguments, and body.
Returns the function binding.

 Clojure:
 (println (fn value1 value2))

 Java:
 System.out.println(fn(value1, value2));
S-Expressions
 Clojure:
 (defn fn [arg1 & more] arg1)


defn is a macro used here with 3 parameters:
function name, arguments, and body.
Returns the function binding.

 Clojure:
 (println (fn value1 value2))

 Java:
 System.out.println(fn(value1, value2));
ring framework
(ns twitturl.core
  (:require [com.twinql.clojure.http :as http])
  (:use [ring.middleware.params])
  (:use [hiccup.core]))

                                       Import dependencies


(defn handler [] nil)      ;todo create handler

(def app (-> handler wrap-params))

                  -> operator used apply multiple
  Entry point          functions to handler
De-structuring
(defn format-tweets [json] nil) ; todo

(defn handler [{{q "q"} :params}]
  { :content-type "text/html"
    :body (html [:body
      (-> (search q) format-tweets)])})

same as:                                 Only need q

(defn handler [request]
  (let [params (request :params)        Local variable assignments
        q      (params "q")]               request and params
    {:content-type "text/html"                 unnecessary.
     :body (html [:body
       (-> (search q) format-tweets)])}))
The Search
(def url "http://search.twitter.com/search.json")

   define readonly variable named url



(defn search [query]
  (http/get url :query {:q query} :as :json))

  returns result of com.twinql.clojure.http.get
  using parameter list
  1)   url
  2)   :query
  3)   {:q query }
  4)   :as
  5)   :json
Enter the repl
% lein deps
Copying 22 files to /Users/kurtharriger/code/twitturl/lib
Copying 17 files to /Users/kurtharriger/code/twitturl/lib/dev

% lein repl
REPL started; server listening on localhost:24319.
user=> (use ‘twitturl.core)
nil
user=> (search “clojure”)

{:code 200,
  :reason "OK",
  :content
   {:results
     [{:from_user "planetclojure",
       :text "Removing defined tests in Clojure REPL
              http://goo.gl/fb/qeUty #clojure #SO",
      ...
     }, ...]
   }
}
The Handler
(defn format-tweets [json] nil) ; todo

(defn handler [{{q "q"} :params}]
  { :content-type "text/html"
    :body        hiccup library function

      (html [:body
        (-> (search q) format-tweets)])})

           same as (format-tweets (search q))


 returns a map containing
 :content-type and :body
functions
(defn aslink [url]
   (html [:a {:href url} url]))
user=> (aslink “http://url1”)
"<a href="http://url1">http://url1</a>"


(def urls (partial re-seq #"http://S+"))
same as:
(defn urls [text] (re-seq #“http://S+” text))

user=> (urls “blah blah http://url1 http://url2”)
("http://url1" "http://url2")
map reduce
(defn linkify [text]
  (reduce #(.replace %1 %2 (aslink %2))
     text (urls text)))
               (fn [newText url]
                  (.replace newText url (aslink url))


String linkify(String text) {
  String newText = text;
  for(String url : getUrls(text)) {
    newText = newText.replace(url, asLink(url));
  }
  return newText;
}
chaining
(defn format-tweet [tweet]   1         2
  [:li (:from_user tweet)
    [:blockquote (-> tweet :text linkify)]])

 Java:

 linkify(tweet.get(“text”))
chaining
(defn format-tweet [tweet]   1         2 2
  [:li (:from_user tweet)
    [:blockquote (-> tweet :text linkify)]])

 Java:

 linkify(tweet.get(“text”))
                                               4


           Java requires more(parentheses)?!
chaining
(defn format-tweets [json]
  [:ul (->> json :content :results
            (remove #(-> % :text urls nil?))
            (map format-tweet))])
ArrayList<String> formatTweets(JSONObject json) {
      StringBuilder tweets = new StringBuilder();
      tweets.append(“<ul>”);
      JSONObject content = json.getJSONObject(“content”);
      JSONArray results = json.getJSONArray(“results”);
      for(JSONObject tweet : results) {
         String[] urls = getUrls(tweet.getString(“text”))
         if(urls != null && urls.length > 0) {
           tweets.append(“<li>” + formatTweet(tweet) “</li>”);
         }
      }
      tweets.append(“</ul>”);
      return tweets;
}
chaining
(defn format-tweets [json]            5
  [:ul (->> json :content :results
            (remove #(-> % :text urls nil?))
            (map format-tweet))])
ArrayList<String> formatTweets(JSONObject json) {
      StringBuilder tweets = new StringBuilder();
      tweets.append(“<ul>”);
      JSONObject content = json.getJSONObject(“content”);
      JSONArray results = json.getJSONArray(“results”);
      for(JSONObject tweet : results) {
                                                                 12
         String[] urls = getUrls(tweet.getString(“text”))
         if(urls != null && urls.length > 0) {
           tweets.append(“<li>” + formatTweet(tweet) “</li>”);
         }
      }
            Java usually requires more(parentheses)?!
      tweets.append(“</ul>”);
      return tweets;
}
ring server
% lein ring server
2011-04-16 21:18:54.965:INFO::Logging to STDERR via org.mortbay.log.StdErrLog

2011-04-16 21:18:54.968:INFO::jetty-6.1.26

2011-04-16 21:18:54.998:INFO::Started SocketConnector@0.0.0.0:3000

Started server on port 3000



% lein ring war
Created /Users/kurtharriger/code/twitturl/twitturl-1.0.0-SNAPSHOT.war




Amazon Elastic Beanstalk plugin
https://github.com/weavejester/lein-beanstalk
src/twitturl/core.clj
 1   (ns twitturl.core
 2     (:use [ring.middleware.params])
 3     (:use [hiccup.core])
 4     (:require [com.twinql.clojure.http :as http]))
 5
 6   (def url "http://search.twitter.com/search.json")
 7
 8   (defn search [query] (http/get url :query {:q query} :as :json))
 9   (defn aslink [url] (html [:a {:href url} url]))
10
11   (def   urls (partial re-seq #"http://S+"))
12
13   (defn linkify [text]
14     (reduce #(.replace %1 %2 (aslink %2)) text (urls text)))
15
16   (defn format-tweet [tweet]
17     [:li (:from_user tweet)
18      [:blockquote (-> tweet :text linkify)]])
19
20   (defn format-tweets [json]
21     [:ul (->> json :content :results
22               (remove #(-> % :text urls nil?))
23               (map format-tweet))])
24
25   (defn handler [{{q "q"} :params}]
26     { :content-type "text/html"
27      :body (html [:body (-> (search q) format-tweets)])})
28
29   (def app (-> handler wrap-params ))
Finding Clojure
    https://github.com/kurtharriger/twitturl
     Leiningen                Ring framework

     DSLs                     Lists are awesome

     Less () than Java        De-structuring

     Method chaining          High-order functions

Kurt Harriger            @kurtharriger

Mais conteúdo relacionado

Mais procurados

Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Tsuyoshi Yamamoto
 
"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014Henning Jacobs
 
The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185Mahmoud Samir Fayed
 
The Ring programming language version 1.6 book - Part 15 of 189
The Ring programming language version 1.6 book - Part 15 of 189The Ring programming language version 1.6 book - Part 15 of 189
The Ring programming language version 1.6 book - Part 15 of 189Mahmoud Samir Fayed
 
QA Fest 2019. Saar Rachamim. Developing Tools, While Testing
QA Fest 2019. Saar Rachamim. Developing Tools, While TestingQA Fest 2019. Saar Rachamim. Developing Tools, While Testing
QA Fest 2019. Saar Rachamim. Developing Tools, While TestingQAFest
 
The Ring programming language version 1.10 book - Part 56 of 212
The Ring programming language version 1.10 book - Part 56 of 212The Ring programming language version 1.10 book - Part 56 of 212
The Ring programming language version 1.10 book - Part 56 of 212Mahmoud Samir Fayed
 
The Ring programming language version 1.7 book - Part 16 of 196
The Ring programming language version 1.7 book - Part 16 of 196The Ring programming language version 1.7 book - Part 16 of 196
The Ring programming language version 1.7 book - Part 16 of 196Mahmoud Samir Fayed
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 SpringKiyotaka Oku
 
Python in the database
Python in the databasePython in the database
Python in the databasepybcn
 
GeeCON 2013 - EJB application guided by tests
GeeCON 2013 - EJB application guided by testsGeeCON 2013 - EJB application guided by tests
GeeCON 2013 - EJB application guided by testsJakub Marchwicki
 
C# Application program UNIT III
C# Application program UNIT IIIC# Application program UNIT III
C# Application program UNIT IIIMinu Rajasekaran
 
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、GaelykでハンズオンTsuyoshi Yamamoto
 
The Ring programming language version 1.5.1 book - Part 24 of 180
The Ring programming language version 1.5.1 book - Part 24 of 180The Ring programming language version 1.5.1 book - Part 24 of 180
The Ring programming language version 1.5.1 book - Part 24 of 180Mahmoud Samir Fayed
 
VPN Access Runbook
VPN Access RunbookVPN Access Runbook
VPN Access RunbookTaha Shakeel
 
Finch.io - Purely Functional REST API with Finagle
Finch.io - Purely Functional REST API with FinagleFinch.io - Purely Functional REST API with Finagle
Finch.io - Purely Functional REST API with FinagleVladimir Kostyukov
 
201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harianKhairunnisaPekanbaru
 

Mais procurados (20)

Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察
 
"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014
 
The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185
 
The Ring programming language version 1.6 book - Part 15 of 189
The Ring programming language version 1.6 book - Part 15 of 189The Ring programming language version 1.6 book - Part 15 of 189
The Ring programming language version 1.6 book - Part 15 of 189
 
Crawler 2
Crawler 2Crawler 2
Crawler 2
 
QA Fest 2019. Saar Rachamim. Developing Tools, While Testing
QA Fest 2019. Saar Rachamim. Developing Tools, While TestingQA Fest 2019. Saar Rachamim. Developing Tools, While Testing
QA Fest 2019. Saar Rachamim. Developing Tools, While Testing
 
The Ring programming language version 1.10 book - Part 56 of 212
The Ring programming language version 1.10 book - Part 56 of 212The Ring programming language version 1.10 book - Part 56 of 212
The Ring programming language version 1.10 book - Part 56 of 212
 
The Ring programming language version 1.7 book - Part 16 of 196
The Ring programming language version 1.7 book - Part 16 of 196The Ring programming language version 1.7 book - Part 16 of 196
The Ring programming language version 1.7 book - Part 16 of 196
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
Hadoop
HadoopHadoop
Hadoop
 
Python in the database
Python in the databasePython in the database
Python in the database
 
GeeCON 2013 - EJB application guided by tests
GeeCON 2013 - EJB application guided by testsGeeCON 2013 - EJB application guided by tests
GeeCON 2013 - EJB application guided by tests
 
C# Application program UNIT III
C# Application program UNIT IIIC# Application program UNIT III
C# Application program UNIT III
 
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
名古屋SGGAE/J勉強会 Grails、Gaelykでハンズオン
 
The Ring programming language version 1.5.1 book - Part 24 of 180
The Ring programming language version 1.5.1 book - Part 24 of 180The Ring programming language version 1.5.1 book - Part 24 of 180
The Ring programming language version 1.5.1 book - Part 24 of 180
 
Perl Web Client
Perl Web ClientPerl Web Client
Perl Web Client
 
VPN Access Runbook
VPN Access RunbookVPN Access Runbook
VPN Access Runbook
 
Finch.io - Purely Functional REST API with Finagle
Finch.io - Purely Functional REST API with FinagleFinch.io - Purely Functional REST API with Finagle
Finch.io - Purely Functional REST API with Finagle
 
Fia fabila
Fia fabilaFia fabila
Fia fabila
 
201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian
 

Destaque (6)

Git Going With DVCS v1.5.2
Git Going With DVCS v1.5.2Git Going With DVCS v1.5.2
Git Going With DVCS v1.5.2
 
Job Hunting Under Duress
Job Hunting Under DuressJob Hunting Under Duress
Job Hunting Under Duress
 
Taming The JVM
Taming The JVMTaming The JVM
Taming The JVM
 
Git Going With DVCS v1.1
Git Going With DVCS v1.1Git Going With DVCS v1.1
Git Going With DVCS v1.1
 
Finding Things in Git
Finding Things in GitFinding Things in Git
Finding Things in Git
 
JQuery Mobile
JQuery MobileJQuery Mobile
JQuery Mobile
 

Semelhante a Finding Clojure

The Ring programming language version 1.10 book - Part 50 of 212
The Ring programming language version 1.10 book - Part 50 of 212The Ring programming language version 1.10 book - Part 50 of 212
The Ring programming language version 1.10 book - Part 50 of 212Mahmoud Samir Fayed
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSTechWell
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsAlessandro Molina
 
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...Fons Sonnemans
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Frameworkless Web Development in Clojure
Frameworkless Web Development in ClojureFrameworkless Web Development in Clojure
Frameworkless Web Development in ClojureKungi2342
 
リローダブルClojureアプリケーション
リローダブルClojureアプリケーションリローダブルClojureアプリケーション
リローダブルClojureアプリケーションKenji Nakamura
 
お題でGroovyプログラミング: Part A
お題でGroovyプログラミング: Part Aお題でGroovyプログラミング: Part A
お題でGroovyプログラミング: Part AKazuchika Sekiya
 
The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202Mahmoud Samir Fayed
 
Clojure in the Wild
Clojure in the WildClojure in the Wild
Clojure in the Wildsuitzero
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
Analysing Github events with Neo4j
Analysing Github events with Neo4jAnalysing Github events with Neo4j
Analysing Github events with Neo4jChristophe Willemsen
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDMichele Capra
 
The Ring programming language version 1.5.3 book - Part 40 of 184
The Ring programming language version 1.5.3 book - Part 40 of 184The Ring programming language version 1.5.3 book - Part 40 of 184
The Ring programming language version 1.5.3 book - Part 40 of 184Mahmoud Samir Fayed
 
Paris js extensions
Paris js extensionsParis js extensions
Paris js extensionserwanl
 

Semelhante a Finding Clojure (20)

Play!ng with scala
Play!ng with scalaPlay!ng with scala
Play!ng with scala
 
The Ring programming language version 1.10 book - Part 50 of 212
The Ring programming language version 1.10 book - Part 50 of 212The Ring programming language version 1.10 book - Part 50 of 212
The Ring programming language version 1.10 book - Part 50 of 212
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOS
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
 
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Frameworkless Web Development in Clojure
Frameworkless Web Development in ClojureFrameworkless Web Development in Clojure
Frameworkless Web Development in Clojure
 
リローダブルClojureアプリケーション
リローダブルClojureアプリケーションリローダブルClojureアプリケーション
リローダブルClojureアプリケーション
 
お題でGroovyプログラミング: Part A
お題でGroovyプログラミング: Part Aお題でGroovyプログラミング: Part A
お題でGroovyプログラミング: Part A
 
The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202
 
Clojure in the Wild
Clojure in the WildClojure in the Wild
Clojure in the Wild
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Web api's
Web api'sWeb api's
Web api's
 
Analysing Github events with Neo4j
Analysing Github events with Neo4jAnalysing Github events with Neo4j
Analysing Github events with Neo4j
 
Html5 For Jjugccc2009fall
Html5 For Jjugccc2009fallHtml5 For Jjugccc2009fall
Html5 For Jjugccc2009fall
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDD
 
Pdxpugday2010 pg90
Pdxpugday2010 pg90Pdxpugday2010 pg90
Pdxpugday2010 pg90
 
The Ring programming language version 1.5.3 book - Part 40 of 184
The Ring programming language version 1.5.3 book - Part 40 of 184The Ring programming language version 1.5.3 book - Part 40 of 184
The Ring programming language version 1.5.3 book - Part 40 of 184
 
TwitterLib.js
TwitterLib.jsTwitterLib.js
TwitterLib.js
 
Paris js extensions
Paris js extensionsParis js extensions
Paris js extensions
 

Mais de Matthew McCullough

Using Git and GitHub Effectively at Emerge Interactive
Using Git and GitHub Effectively at Emerge InteractiveUsing Git and GitHub Effectively at Emerge Interactive
Using Git and GitHub Effectively at Emerge InteractiveMatthew McCullough
 
All About GitHub Pull Requests
All About GitHub Pull RequestsAll About GitHub Pull Requests
All About GitHub Pull RequestsMatthew McCullough
 
Git Graphs, Hashes, and Compression, Oh My
Git Graphs, Hashes, and Compression, Oh MyGit Graphs, Hashes, and Compression, Oh My
Git Graphs, Hashes, and Compression, Oh MyMatthew McCullough
 
Git and GitHub at the San Francisco JUG
 Git and GitHub at the San Francisco JUG Git and GitHub at the San Francisco JUG
Git and GitHub at the San Francisco JUGMatthew McCullough
 
Migrating from Subversion to Git and GitHub
Migrating from Subversion to Git and GitHubMigrating from Subversion to Git and GitHub
Migrating from Subversion to Git and GitHubMatthew McCullough
 
Build Lifecycle Craftsmanship for the Transylvania JUG
Build Lifecycle Craftsmanship for the Transylvania JUGBuild Lifecycle Craftsmanship for the Transylvania JUG
Build Lifecycle Craftsmanship for the Transylvania JUGMatthew McCullough
 
Git Going for the Transylvania JUG
Git Going for the Transylvania JUGGit Going for the Transylvania JUG
Git Going for the Transylvania JUGMatthew McCullough
 
Transylvania JUG Pre-Meeting Announcements
Transylvania JUG Pre-Meeting AnnouncementsTransylvania JUG Pre-Meeting Announcements
Transylvania JUG Pre-Meeting AnnouncementsMatthew McCullough
 
Game Theory for Software Developers at the Boulder JUG
Game Theory for Software Developers at the Boulder JUGGame Theory for Software Developers at the Boulder JUG
Game Theory for Software Developers at the Boulder JUGMatthew McCullough
 
Cascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUGCascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUGMatthew McCullough
 

Mais de Matthew McCullough (20)

Using Git and GitHub Effectively at Emerge Interactive
Using Git and GitHub Effectively at Emerge InteractiveUsing Git and GitHub Effectively at Emerge Interactive
Using Git and GitHub Effectively at Emerge Interactive
 
All About GitHub Pull Requests
All About GitHub Pull RequestsAll About GitHub Pull Requests
All About GitHub Pull Requests
 
Adam Smith Builds an App
Adam Smith Builds an AppAdam Smith Builds an App
Adam Smith Builds an App
 
Git's Filter Branch Command
Git's Filter Branch CommandGit's Filter Branch Command
Git's Filter Branch Command
 
Git Graphs, Hashes, and Compression, Oh My
Git Graphs, Hashes, and Compression, Oh MyGit Graphs, Hashes, and Compression, Oh My
Git Graphs, Hashes, and Compression, Oh My
 
Git and GitHub at the San Francisco JUG
 Git and GitHub at the San Francisco JUG Git and GitHub at the San Francisco JUG
Git and GitHub at the San Francisco JUG
 
Git and GitHub for RallyOn
Git and GitHub for RallyOnGit and GitHub for RallyOn
Git and GitHub for RallyOn
 
Migrating from Subversion to Git and GitHub
Migrating from Subversion to Git and GitHubMigrating from Subversion to Git and GitHub
Migrating from Subversion to Git and GitHub
 
Git Notes and GitHub
Git Notes and GitHubGit Notes and GitHub
Git Notes and GitHub
 
Intro to Git and GitHub
Intro to Git and GitHubIntro to Git and GitHub
Intro to Git and GitHub
 
Build Lifecycle Craftsmanship for the Transylvania JUG
Build Lifecycle Craftsmanship for the Transylvania JUGBuild Lifecycle Craftsmanship for the Transylvania JUG
Build Lifecycle Craftsmanship for the Transylvania JUG
 
Git Going for the Transylvania JUG
Git Going for the Transylvania JUGGit Going for the Transylvania JUG
Git Going for the Transylvania JUG
 
Transylvania JUG Pre-Meeting Announcements
Transylvania JUG Pre-Meeting AnnouncementsTransylvania JUG Pre-Meeting Announcements
Transylvania JUG Pre-Meeting Announcements
 
Game Theory for Software Developers at the Boulder JUG
Game Theory for Software Developers at the Boulder JUGGame Theory for Software Developers at the Boulder JUG
Game Theory for Software Developers at the Boulder JUG
 
Cascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUGCascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUG
 
R Data Analysis Software
R Data Analysis SoftwareR Data Analysis Software
R Data Analysis Software
 
Please, Stop Using Git
Please, Stop Using GitPlease, Stop Using Git
Please, Stop Using Git
 
Dr. Strangedev
Dr. StrangedevDr. Strangedev
Dr. Strangedev
 
Jenkins for One
Jenkins for OneJenkins for One
Jenkins for One
 
Lean Fluffy Startups
Lean Fluffy StartupsLean Fluffy Startups
Lean Fluffy Startups
 

Último

SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 

Último (20)

SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 

Finding Clojure

  • 3. Project Folder % lein new twitturl Created new project in: /Users/kurtharriger/code/twitturl ├── README ├── project.clj ├── src │   └── twitturl │   └── core.clj └── test └── twitturl └── test └── core.clj % git init && git add -A && git commit -m “create project”
  • 4. project.clj (defproject twitturl "1.0.0-SNAPSHOT" :description "Twitturl aggregator" :dependencies [[org.clojure/clojure "1.2.0"] [org.clojure/clojure-contrib "1.2.0"] [ring "0.3.7"] [clj-http "0.1.2"]] :dev-dependencies [[lein-ring "0.4.0"]] :ring {:handler twitturl.core/app})
  • 5. Appleholics % brew install leiningen Non Appleholics Find Leiningen for Clojure on https://github.com/technomancy/leiningen % lein self-install
  • 6. S-Expressions Clojure: (defn fn [arg1 & more] arg1) defn is a macro used here with 3 parameters: function name, arguments, and body. Returns the function binding. Clojure: (println (fn value1 value2)) Java: System.out.println(fn(value1, value2));
  • 7. S-Expressions Clojure: (defn fn [arg1 & more] arg1) defn is a macro used here with 3 parameters: function name, arguments, and body. Returns the function binding. Clojure: (println (fn value1 value2)) Java: System.out.println(fn(value1, value2));
  • 8. ring framework (ns twitturl.core (:require [com.twinql.clojure.http :as http]) (:use [ring.middleware.params]) (:use [hiccup.core])) Import dependencies (defn handler [] nil) ;todo create handler (def app (-> handler wrap-params)) -> operator used apply multiple Entry point functions to handler
  • 9. De-structuring (defn format-tweets [json] nil) ; todo (defn handler [{{q "q"} :params}] { :content-type "text/html" :body (html [:body (-> (search q) format-tweets)])}) same as: Only need q (defn handler [request] (let [params (request :params) Local variable assignments q (params "q")] request and params {:content-type "text/html" unnecessary. :body (html [:body (-> (search q) format-tweets)])}))
  • 10. The Search (def url "http://search.twitter.com/search.json") define readonly variable named url (defn search [query] (http/get url :query {:q query} :as :json)) returns result of com.twinql.clojure.http.get using parameter list 1) url 2) :query 3) {:q query } 4) :as 5) :json
  • 11. Enter the repl % lein deps Copying 22 files to /Users/kurtharriger/code/twitturl/lib Copying 17 files to /Users/kurtharriger/code/twitturl/lib/dev % lein repl REPL started; server listening on localhost:24319. user=> (use ‘twitturl.core) nil user=> (search “clojure”) {:code 200, :reason "OK", :content {:results [{:from_user "planetclojure", :text "Removing defined tests in Clojure REPL http://goo.gl/fb/qeUty #clojure #SO", ... }, ...] } }
  • 12. The Handler (defn format-tweets [json] nil) ; todo (defn handler [{{q "q"} :params}] { :content-type "text/html" :body hiccup library function (html [:body (-> (search q) format-tweets)])}) same as (format-tweets (search q)) returns a map containing :content-type and :body
  • 13. functions (defn aslink [url] (html [:a {:href url} url])) user=> (aslink “http://url1”) "<a href="http://url1">http://url1</a>" (def urls (partial re-seq #"http://S+")) same as: (defn urls [text] (re-seq #“http://S+” text)) user=> (urls “blah blah http://url1 http://url2”) ("http://url1" "http://url2")
  • 14. map reduce (defn linkify [text] (reduce #(.replace %1 %2 (aslink %2)) text (urls text))) (fn [newText url] (.replace newText url (aslink url)) String linkify(String text) { String newText = text; for(String url : getUrls(text)) { newText = newText.replace(url, asLink(url)); } return newText; }
  • 15. chaining (defn format-tweet [tweet] 1 2 [:li (:from_user tweet) [:blockquote (-> tweet :text linkify)]]) Java: linkify(tweet.get(“text”))
  • 16. chaining (defn format-tweet [tweet] 1 2 2 [:li (:from_user tweet) [:blockquote (-> tweet :text linkify)]]) Java: linkify(tweet.get(“text”)) 4 Java requires more(parentheses)?!
  • 17. chaining (defn format-tweets [json] [:ul (->> json :content :results (remove #(-> % :text urls nil?)) (map format-tweet))]) ArrayList<String> formatTweets(JSONObject json) { StringBuilder tweets = new StringBuilder(); tweets.append(“<ul>”); JSONObject content = json.getJSONObject(“content”); JSONArray results = json.getJSONArray(“results”); for(JSONObject tweet : results) { String[] urls = getUrls(tweet.getString(“text”)) if(urls != null && urls.length > 0) { tweets.append(“<li>” + formatTweet(tweet) “</li>”); } } tweets.append(“</ul>”); return tweets; }
  • 18. chaining (defn format-tweets [json] 5 [:ul (->> json :content :results (remove #(-> % :text urls nil?)) (map format-tweet))]) ArrayList<String> formatTweets(JSONObject json) { StringBuilder tweets = new StringBuilder(); tweets.append(“<ul>”); JSONObject content = json.getJSONObject(“content”); JSONArray results = json.getJSONArray(“results”); for(JSONObject tweet : results) { 12 String[] urls = getUrls(tweet.getString(“text”)) if(urls != null && urls.length > 0) { tweets.append(“<li>” + formatTweet(tweet) “</li>”); } } Java usually requires more(parentheses)?! tweets.append(“</ul>”); return tweets; }
  • 19. ring server % lein ring server 2011-04-16 21:18:54.965:INFO::Logging to STDERR via org.mortbay.log.StdErrLog 2011-04-16 21:18:54.968:INFO::jetty-6.1.26 2011-04-16 21:18:54.998:INFO::Started SocketConnector@0.0.0.0:3000 Started server on port 3000 % lein ring war Created /Users/kurtharriger/code/twitturl/twitturl-1.0.0-SNAPSHOT.war Amazon Elastic Beanstalk plugin https://github.com/weavejester/lein-beanstalk
  • 20.
  • 21. src/twitturl/core.clj 1 (ns twitturl.core 2 (:use [ring.middleware.params]) 3 (:use [hiccup.core]) 4 (:require [com.twinql.clojure.http :as http])) 5 6 (def url "http://search.twitter.com/search.json") 7 8 (defn search [query] (http/get url :query {:q query} :as :json)) 9 (defn aslink [url] (html [:a {:href url} url])) 10 11 (def urls (partial re-seq #"http://S+")) 12 13 (defn linkify [text] 14 (reduce #(.replace %1 %2 (aslink %2)) text (urls text))) 15 16 (defn format-tweet [tweet] 17 [:li (:from_user tweet) 18 [:blockquote (-> tweet :text linkify)]]) 19 20 (defn format-tweets [json] 21 [:ul (->> json :content :results 22 (remove #(-> % :text urls nil?)) 23 (map format-tweet))]) 24 25 (defn handler [{{q "q"} :params}] 26 { :content-type "text/html" 27 :body (html [:body (-> (search q) format-tweets)])}) 28 29 (def app (-> handler wrap-params ))
  • 22. Finding Clojure https://github.com/kurtharriger/twitturl Leiningen Ring framework DSLs Lists are awesome Less () than Java De-structuring Method chaining High-order functions Kurt Harriger @kurtharriger