Skip to content

Instantly share code, notes, and snippets.

@zyuiop
Created May 26, 2019 19:16
Show Gist options
  • Save zyuiop/ff88a5f02680f701b1a3ea627757af3e to your computer and use it in GitHub Desktop.
Save zyuiop/ff88a5f02680f701b1a3ea627757af3e to your computer and use it in GitHub Desktop.
name := "euro_tracker"
version := "0.1"
scalaVersion := "2.12.8"
libraryDependencies += "org.jsoup" % "jsoup" % "1.8.3"
import java.util.Date
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import scala.collection.mutable
import scala.io.{AnsiColor, Source}
/**
* @author Louis Vialar
*/
object EuroTracker {
private val previousPercent: mutable.Map[String, Double] = mutable.Map()
private val previousVotes: mutable.Map[String, Int] = mutable.Map()
private var previousTotal: Int = 0
def main(args: Array[String]) = {
while (previousTotal < 100) {
try {
loadResults()
Thread.sleep(1000)
} catch {
case _ =>
}
}
}
def loadResults(): Any = {
val doc = Jsoup.connect("https://elections.interieur.gouv.fr/europeennes-2019/FE.html").get()
val elts = doc.select("tr")
val title = doc.select("h4").first().child(0).text().filter(_.isDigit)
val time = new Date()
val nTot = title.toInt
if (nTot <= previousTotal)
return
previousTotal = nTot
println()
println("Partis éligibles à " + AnsiColor.CYAN + time + AnsiColor.RESET + " -- " + AnsiColor.RED + title + "% " + AnsiColor.RESET + "des bulletins ")
elts.forEach(elt => {
if (elt.child(0).tagName() == "td" && elt.child(0).children().size() > 0 && elt.child(0).child(0).tagName() == "a" && elt.children().size() >= 4) {
val party = elt.child(0).child(0).text()
val votes = elt.child(1).text()
val expressed = elt.child(3).text()
val votesInt = votes.filter(_.isDigit).toInt
val expressedDouble = expressed.filter(c => c.isDigit || c == ',').replace(',', '.').toDouble
if (expressedDouble < 5.0) return
val percent = previousPercent.put(party, expressedDouble)
.map(prev => expressedDouble - prev)
.flatMap(v => {
if (v > 0) {
Some(AnsiColor.GREEN + " [+ " + v.formatted("%.2f") + " %]" + AnsiColor.RESET)
} else if (v < 0) {
Some(AnsiColor.RED + " [" + v.formatted("%.2f") + " %]" + AnsiColor.RESET)
} else None
}).getOrElse("")
val previous = previousVotes.put(party, votesInt).map(prev => votesInt - prev)
.flatMap(v => {
if (v > 0) {
Some(AnsiColor.GREEN + " [+ " + v + "]" + AnsiColor.RESET)
} else if (v < 0) {
Some(AnsiColor.RED + " [" + v + "]" + AnsiColor.RESET)
} else None
}).getOrElse("")
println(s"Parti ${AnsiColor.CYAN}'$party'${AnsiColor.RESET} ==> ${AnsiColor.GREEN}$votes$previous ($expressed %$percent)${AnsiColor.RESET}")
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment