我正在尝试学习Java,Scala和Clojure.
我正在研究三种语言的Project Euler问题.下面列出了问题#5(http://projecteuler.net/problem=5)的代码以及前五个问题的运行时间(以秒为单位).令我惊讶的是Java和Clojure版本比问题#5的Scala慢得多.它们运行在同一台机器上,相同的jvm,结果在几次试验中是一致的.我能做些什么来加速这两个(特别是Clojure版本)?为什么Scala版本更快?
|---------|--------|--------|----------|
| problem | Java | Scala | Clojure |
|=========|========|========|==========|
| 1 | .0010 | .1570 | .0116 |
| 2 | .0120 | .0030 | .0003 |
| 3 | .0530 | .0200 | .1511 |
| 4 | .2120 | .2600 | .8387 |
| 5 | 3.9680 | .3020 | 33.8574 |
Run Code Online (Sandbox Code Playgroud)
public class Problem005 {
private static ArrayList<Integer> divisors;
private static void initializeDivisors(int ceiling) {
divisors = new …Run Code Online (Sandbox Code Playgroud) 我有一个Map [Int,Int]列表,它们都有相同的键(从1到20),我想将它们的内容合并到一个Map [Int,Int]中.
我已经阅读了关于合并使用|+|scalaz库的地图的堆栈溢出的另一篇文章.
我想出了以下解决方案,但对我来说似乎很笨拙.
val defaultMap = (2 to ceiling).map((_,0)).toMap
val factors: Map[Int, Int] = (2 to ceiling). map(primeFactors(_)).
foldRight(defaultMap)(mergeMaps(_, _))
def mergeMaps(xm: Map[Int, Int], ym: Map[Int, Int]): Map[Int,Int] = {
def iter(acc: Map[Int,Int], other: Map[Int,Int], i: Int): Map[Int,Int] = {
if (other.isEmpty) acc
else iter(acc - i + (i -> math.max(acc(i), other(i))), other - i, i + 1)
}
iter(xm, ym, 2)
}
def primeFactors(number: Int): Map[Int, Int] = {
def iter(factors: …Run Code Online (Sandbox Code Playgroud) 我正在使用Slick 1.0.1运行Scala Play 2.2应用程序.我试图将所有数据库调用包装到将来的尝试中,例如:
object DbTeachers extends Table[DbTeacher]("edu_teachers") {
...
def insertTeacher(school: Int, userId: String)
(implicit ec: ExecutionContext, db: Database) =
future { Try { db.withSession => { implicit s: Session =>
(DbTeachers.school ~ DbTeachers.teacher).insert(school, userId)
}}}
}
Run Code Online (Sandbox Code Playgroud)
我发现该模式future { Try { db.withSession => { ACTUAL_CODE_GOES_HERE }}}会产生混乱,我想将其抽象如下:
sealed class DbAsync[T](block: => T) {
import play.api.libs.concurrent.Execution.Implicits.defaultContext
implicit lazy val db = Database.forDataSource(DB.getDataSource())
def get: Future[Try[T]] = future { Try { db.withSession { implicit s: Session =>
block
}}}
} …Run Code Online (Sandbox Code Playgroud) 我正在尝试学习算法和java.运行320x320的网格,100次试验比非递归的Quick-Union实施快5倍.但是,超过大约400x400(160,000个站点)的网格,我有堆栈溢出错误.
我知道java没有针对尾递归进行优化(更不用说非尾递归)了.但是,我认为有时可以选择递归算法而不是非递归版本,因为它可以更快地运行并且同样安全.
请记住,我只是在学习这些东西,而我的代码可能不是最佳的.但是,为了更好地理解我的问题,我将其包括在内.
当递归算法可以安全地在java应用程序中使用时,评估的过程是什么(假设它比非递归替代方案运行得更快)?
(注意:2x比率只是前一个当前运行时间除以前一个运行时间)
|-----------|-----------|------------|-------------|-------------|
| N | Recursive | Recursive | Quick-Union | Quick-Union |
| (sites) | time | 2x Ratio | time | 2x Ratio |
|===========|===========|============|=============|=============|
| 196 | 35 | | 42 | |
| 400 | 25 | 0.71 | 44 | 1.05 |
| 784 | 45 | 1.80 | 46 | 1.05 |
| 1600 | 107 | 2.38 | 86 | 1.87 |
| 3136 | 48 …Run Code Online (Sandbox Code Playgroud) 我正在为连接到Google云端硬盘的应用使用服务器端流量验证.
我能够检索访问代码并交换access_token和用户信息.然后我坚持使用refresh_token.所以,我可以确认client_id和client_secret是正确的,但是当我使用refresh_token获取新的access_token时,我得到400响应.这是详细信息,我记录了来自初始令牌请求的响应,并且可以确认存储到数据库的refresh_token与来自Google的响应中的refresh_token匹配.
但是当我尝试使用refresh_token(以编程方式并使用httpie)时,我得到以下响应.为什么?
% http --verbose POST https://accounts.google.com/o/oauth2/token Content-Type:application/x-www-form-urlencoded refresh_token=1/nJZGF7hIySVtVCl8I-Y3KfXAPk84gD0X6ym7hQS8gcc client_id=XXXX client_secret=XXXX grant_type=refresh_token
POST /o/oauth2/token HTTP/1.1
Content-Length: 198
Host: accounts.google.com
b'Accept': application/json
b'Accept-Encoding': gzip, deflate, compress
b'Content-Type': application/x-www-form-urlencoded
b'User-Agent': HTTPie/0.6.0
{"refresh_token": "1/nJZGF7hIySVtVCl8I-Y3KfXAPk84gD0X6ym7hQS8gcc", "client_id": "XXXX", "client_secret": "XXXX", "grant_type": "refresh_token"}
HTTP/1.1 400 Bad Request
Alternate-Protocol: 443:quic
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Type: application/json
Date: Mon, 16 Sep 2013 03:42:06 GMT
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Pragma: no-cache
Server: GSE
Transfer-Encoding: chunked
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block …Run Code Online (Sandbox Code Playgroud) 我有一个scala.html页面,它在Play 2.2.1,Scala 2.10.2,Slick 1.0.1,Postgres 9.3应用程序中进行AJAX调用.
以下同步代码工作正常.它解析请求查询字符串并调用该方法Schools.findSchoolsByFilter,该方法对表进行scala光滑调用并根据SchoolFilter对象过滤结果并返回Try[List[School]]
def listSchools = Action { implicit request =>
db.withSession { implicit s: Session =>
Schools.findSchoolsByFilter(parseFilter) match {
case Success(schools) => Ok(toJsArray(schools))
case Failure(e) => Ok(e.getMessage)
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我将方法更改为异步运行(见下文),并对listSchools进行多次调用,则在大约20秒后抛出此异常.我怀疑它可能是某种竞争条件,类似于这篇文章播放光滑和异步 - 它是竞争条件吗?.我的问题是,我应该如何更改此代码以安全地异步运行它?
def listSchools = Action.async { implicit request =>
db.withSession { implicit s: Session =>
Schools.findSchoolsByFilter(parseFilter) map {
case Success(schools) => Ok(toJsArray(schools))
case Failure(e) => Ok(e.getMessage)
}
}
}
def findSchoolsByFilter(f: SchoolFilter, n: Int)(implicit s: Session) = …Run Code Online (Sandbox Code Playgroud) 我有一段代码从请求主体中提取字符串,但它可能不存在,所以它是一个Option[String].如果有值,那么我希望隐含地使用它.
为了做这个转换,我写道implicit val code = googleCode.
有没有办法制作googleCode一个隐式字符串,以便我可以直接使用它,而不是创建一个implicit val值为googleCode?
request.getQueryString("code") match {
case None =>
Logger.error("unable to retrieve authentication code from google request")
Redirect(routes.Application.index())
case Some(googleCode) => Async {
implicit val code: String = googleCode // <== CONVERTING TO AN IMPLICIT
Logger.debug("retrieved authentication code, proceeding to get token")
...
Ok("congratulations, ${user.name}, you are logged in!")
Run Code Online (Sandbox Code Playgroud)
请注意,代码段来自Playframework Controller,但这通常是Scala语言的问题