Skip to content

Instantly share code, notes, and snippets.

@andrewconner
andrewconner / FutureGoodies.scala
Last active May 4, 2016 11:34
SafeFuture, TimeoutFuture, CancelableFuture implementations. See https://eng.42go.com/future-safefuture-timeout-cancelable for further explanation.Thanks to @bretthoerner for spotting an error!
/* We've run into a few common pitfalls when dealing with Futures in Scala, so I wrote these three helpful
* classes to give some baked-in functionality.
*
* I'd love to hear about other helpers you're using like these, or if you have improvement suggestions.
* github@andrewconner.org / @connerdelights
*/
import scala.concurrent.{ExecutionContext, CanAwait, Awaitable, Future, Promise}
import scala.concurrent.duration.Duration
import scala.util.Try
| 2546 | youtube.com |
| 865 | facebook.com |
| 632 | docs.google.com |
| 550 | mail.google.com |
| 514 | amazon.com |
| 507 | github.com |
| 499 | google.com |
| 455 | linkedin.com |
| 386 | en.wikipedia.org |
| 378 | techcrunch.com |
@andrewconner
andrewconner / TrimString.scala
Created August 16, 2013 16:51
Trimming a string at a certain number of bytes
import java.nio.{ByteBuffer, CharBuffer}
import java.nio.charset.Charset
def trimAtBytes(str: String, len: Int, charset: Charset) = {
val outBuf = ByteBuffer.wrap(new Array[Byte](len))
val inBuf = CharBuffer.wrap(str.toCharArray())
charset.newEncoder().encode(inBuf, outBuf, true)
new String(outBuf.array, 0, outBuf.position(), charset)
}
// Reverses an integer without using Strings
def reverse(n: Int): Int = {
val len = math.ceil(math.log10(n+1)).toInt
Stream.continually(n).take(len).zipWithIndex
.map{ case (m,p) =>
(m % math.pow(10, len-p) / math.pow(10, len-p-1)).toInt * math.pow(10,p)
}
.sum.toInt
}
@andrewconner
andrewconner / Employee.scala
Created June 21, 2013 22:35
Validating objects during a db save using `Try`
case class Employee(id: Option[Long] = None, name: String, age: Int, salary: Int)
object EmployeeRepo {
private def persist(employee: Employee): Employee = {
// persisting logic
employee.copy(id = Some(10L)) // database returns persisted id, return new object with id set
}
def save(employees: Seq[Employee])(implicit validator: Employee => Try[Employee]): Seq[Try[Employee]] = {
employees.map(validator(_).map(persist))
@andrewconner
andrewconner / KillingPlay.sh
Created June 20, 2013 16:21
Killing a running Play! framework application. First gracefully, and then quite violently.
maxShutdownTime=15
function stopServiceProcess {
kill $pid || return 1
for ((i=0; i<maxShutdownTime*10; i++)); do
checkProcessIsRunning $pid
if [ $? -ne 0 ]; then
rm -f $pidFile
return 0
fi
@andrewconner
andrewconner / UserVoiceTokenGenerator.scala
Last active December 16, 2015 22:59
UserVoice SSO Token Generator in Scala
import org.apache.commons.codec.net.URLCodec
import org.apache.commons.codec.binary.Base64
import javax.crypto.spec.SecretKeySpec
import javax.crypto.spec.IvParameterSpec
import org.apache.commons.codec.digest.DigestUtils
import java.io.InputStream
import java.io.OutputStream
import javax.crypto.Cipher
import javax.crypto.CipherOutputStream
$ curl -i http://www.42go.com/ | grep Server
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 4425 100 4425 0 0 79467 0 --:--:-- --:--:-- --:--:-- 149k
Server: Don't Panic!
trait Translator {
def translate(input: String): String
}
class FrenchTranslatorImpl extends Translator {
val wordReplacements = Map(
"hello" -> "bonjour",
"hi" -> "salut",
"greetings" -> "salutations"
)
def timer(f: => Any): Long = {
val startTime = System.nanoTime
val ret = f
val endTime = System.nanoTime
endTime - startTime
}
def iterTest(f: => Any): Double = {
(for(i <- 0 to 10000) yield timer(f)).sorted.apply(5000)