小编win*_*ner的帖子

为什么scala.util.Failure有一个类型参数?

scala.util.Failure 声明如下:

final case class Failure[+T](exception: Throwable) extends Try[T]`
Run Code Online (Sandbox Code Playgroud)

它需要一个T看起来完全不必要的类型参数,给出如何Failure轻松地声明为子类型Try[Nothing]:

final case class Failure(exception: Throwable) extends Try[Nothing]`
Run Code Online (Sandbox Code Playgroud)

以与None声明相同的方式:

object None extends Option[Nothing]
Run Code Online (Sandbox Code Playgroud)

实际上,额外的类型参数在其他地方成为痛点.这是Future.zip:

def zip[U](that: Future[U]): Future[(T, U)] = {
  implicit val ec = internalExecutor
  val p = Promise[(T, U)]()
  onComplete {
    case f: Failure[_] => p complete f.asInstanceOf[Failure[(T, U)]]
    case Success(s) => that onComplete { c => p.complete(c map { s2 => (s, s2) }) }
  }
  p.future
} …
Run Code Online (Sandbox Code Playgroud)

types scala

11
推荐指数
1
解决办法
473
查看次数

为什么Stream.filter内存不足?

这两个表达式应该是一样的:

Stream.from(1).filter(_ < 0).head
Stream.from(1).find(_ < 0)
Run Code Online (Sandbox Code Playgroud)

应该循环直到它们返回Int.MinValue.这正是版本所具有的filter功能,但是产生了find一个版本OutOfMemoryError.看看他们的实现,我无法弄清楚这两个版本都没有产生OutOfMemoryError.

这是执行Stream.filter:

override def filter(p: A => Boolean): Stream[A] = {
  // optimization: drop leading prefix of elems for which f returns false
  // var rest = this dropWhile (!p(_)) - forget DRY principle - GC can't collect otherwise
  var rest = this
  while (!rest.isEmpty && !p(rest.head)) rest = rest.tail
  // private utility func to avoid `this` on stack (would be …
Run Code Online (Sandbox Code Playgroud)

scala scala-collections

6
推荐指数
1
解决办法
166
查看次数

Seaborn 猫图结合 PairGrid

我正在使用泰坦尼克号数据集,并尝试针对分类变量生成一对数值变量图。我可以使用 Seaborn'scatplot绘制一个数字变量与一个分类变量的图:

import seaborn as sns

sns.catplot(data=train, x='Fare', y='Sex')
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试使用 PairGrid 根据分类变量绘制数字变量:

x_vars = ['Fare']
y_vars = ['Sex']

g = sns.PairGrid(train, x_vars=x_vars, y_vars=y_vars)
g.map(sns.catplot)
Run Code Online (Sandbox Code Playgroud)

它失败并出现错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-75-c284a7cfd727> in <module>
      9 #g.map_diag(lambda x, **kwargs: sns.catplot(x, x, **kwargs), jitter=True, kind="bar")
     10 #g.map(sns.scatterplot, y_jitter=1)#, hue=train["Survived"])
---> 11 g.map(sns.catplot)#, hue=train["Survived"])

~/MLProject/book1/lib/python3.8/site-packages/seaborn/axisgrid.py in map(self, func, **kwargs)
   1363         row_indices, col_indices = np.indices(self.axes.shape)
   1364         indices = zip(row_indices.flat, col_indices.flat)
-> 1365         self._map_bivariate(func, indices, **kwargs)
   1366         return self
   1367 

~/MLProject/book1/lib/python3.8/site-packages/seaborn/axisgrid.py in …
Run Code Online (Sandbox Code Playgroud)

python data-visualization seaborn

6
推荐指数
1
解决办法
1335
查看次数

为什么Fuse迭代器适配器不能按预期工作?

我正在尝试使用Fuse迭代器适配器并获得意外结果(Playground链接):

fn main() {
    let mut i1 = (1..3).scan(1, |_, x| {
        if x < 2 { None } else { Some(x) }
    });
    println!("{:?}", i1.next());
    println!("{:?}", i1.next());
    println!("{:?}", i1.next());
    println!("");

    let mut i2 = (1..3).scan(1, |_, x| {
        if x < 2 { None } else { Some(x) }
    }).fuse();
    println!("{:?}", i2.next());
    println!("{:?}", i2.next()); // This should print None
    println!("{:?}", i2.next());
    println!("");
}
Run Code Online (Sandbox Code Playgroud)

哪个印刷品:

None
Some(2)
None

None
Some(2)
None
Run Code Online (Sandbox Code Playgroud)

迭代器i1正在回归我的期望.它返回None,然后 …

iterator rust

5
推荐指数
1
解决办法
162
查看次数

使用scala akka spray进行非常基本的http服务器测试时出错

我做了一个非常基本的喷雾测试,使用:

  • 阿卡2.10 2.24
  • Scala 2.10.3
  • 喷雾罐1.3.1
  • sbt 0.13
  • IntelliJ 13

这是我的代码:

val myListener: ActorRef = system.actorOf(Props[TestHttpListener], "httpListener")
IO(Http) ! Http.Bind(myListener, interface = "localhost", port = 8080)
Run Code Online (Sandbox Code Playgroud)

httpListener起反应对Http.ConnectedHttp.Register(self).

我使用sbt来运行我的代码.它失败了AbstractMethodError:

[ERROR] [07/12/2014 18:46:48.364] [default-akka.actor.default-dispatcher-5] [ActorSystem(default)] Uncaught error from thread [default-akka.actor.default-dispatcher-5] shutting down JVM since 'akka.jvm-exit-on-fatal-error' is enabled
java.lang.AbstractMethodError: spray.can.HttpManager.akka$actor$ActorLogging$_setter_$log_$eq(Lakka/event/LoggingAdapter;)V
        at akka.actor.ActorLogging$class.$init$(Actor.scala:335)
        at spray.can.HttpManager.<init>(HttpManager.scala:29)
        at spray.can.HttpExt$$anonfun$1.apply(Http.scala:153)
        at spray.can.HttpExt$$anonfun$1.apply(Http.scala:153)
        at akka.actor.TypedCreatorFunctionConsumer.produce(Props.scala:422)
        at akka.actor.Props.newActor(Props.scala:331)
        at akka.actor.ActorCell.newActor(ActorCell.scala:534)
        at akka.actor.ActorCell.create(ActorCell.scala:560)
        at akka.actor.dungeon.FaultHandling$class.finishCreate(FaultHandling.scala:135)
        at akka.actor.dungeon.FaultHandling$class.faultCreate(FaultHandling.scala:129)
        at akka.actor.ActorCell.faultCreate(ActorCell.scala:338)
        at akka.actor.dungeon.FaultHandling$class.faultRecreate(FaultHandling.scala:58)
        at …
Run Code Online (Sandbox Code Playgroud)

scala httpserver akka spray

4
推荐指数
1
解决办法
2409
查看次数

生命周期参数和函数指针的问题

考虑这个代码:

struct WithLifetime<'a> {
    s: &'a str
}

impl WithLifetime<'_> {
    fn in_impl(&self) -> bool {
        self.s == "a"
    }
}

fn out_of_impl(wl: &WithLifetime<'_>) -> bool {
    wl.s == "a"
}

fn higher_order(f: fn(&WithLifetime<'_>) -> bool) -> bool {
    let s = "a";
    let wl = WithLifetime { s };
    f(&wl)
}

fn main() {
    higher_order(out_of_impl); // This line compiles
    higher_order(WithLifetime::in_impl); // This line does not
}
Run Code Online (Sandbox Code Playgroud)

最后一行main由于此错误而无法编译:

error[E0308]: mismatched types
  --> src/main.rs:23:18
   |
23 |     higher_order(WithLifetime::in_impl); // …
Run Code Online (Sandbox Code Playgroud)

rust

3
推荐指数
1
解决办法
125
查看次数

如果选中至少一个复选框,应该启用Angular JS + Button如何执行此操作?

我想要一个仅在选中一组复选框中的一个时才启用的按钮,类似于http://jsfiddle.net/chriscoyier/BPhZe/76中的小提琴:

var checkboxes = $("input[type='checkbox']"),
    submitButt = $("input[type='submit']");

checkboxes.click(function() {
    submitButt.attr("disabled", !checkboxes.is(":checked"));
});
Run Code Online (Sandbox Code Playgroud)

我想用AngularJs来实现它.

angularjs

2
推荐指数
1
解决办法
1万
查看次数

scala中无法访问的代码?

由于某种原因,以下代码无法访问.我无法理解为什么我的代码永远不会到达,因为这是一个简单的模式匹配.这里是:

type Occurrences = List[(Char, Int)]

def combinations(occurrences: Occurrences): List[Occurrences] = occurrences match{
  case Nil => Nil
  case List() => List()
  case x => List(x)
  case x::xs => combinations(List((x._1,x._2 - 1))) ::: combinations(xs)
}
Run Code Online (Sandbox Code Playgroud)

该算法旨在提取给定列表的所有子列表.

scala pattern-matching unreachable-code

1
推荐指数
1
解决办法
2133
查看次数

这是对Scala如何提供多重继承而不引起Diamond问题的正确理解吗?

下面的代码:

trait t1 {
    def printt1 = println("In t1")
}

trait t2 {
    def printt1 = println("In t2")
}

class cclass extends t1 with t2
Run Code Online (Sandbox Code Playgroud)

导致此编译时错误:

class cclass inherits conflicting members: method printt1 in trait t1 of type => Unit and method printt1 in trait t2 
 of type => Unit (Note: this can be resolved by declaring an override in class cclass.)
Run Code Online (Sandbox Code Playgroud)

因此,这提供了编译时检查,该检查不允许多重继承,但允许混合,同时还可以防止Diamond问题:“多年来,多重继承一直是一个棘手的问题[需要引用],反对者指出它的复杂性和歧义性越来越高。 “钻石问题”之类的情况,如果一个以上的父类实现了某个特定功能,则该特定功能是从哪个父类继承的就可能是模棱两可的。” 来源:http : //en.wikipedia.org/wiki/Multiple_inheritance

为了解决上面的编译时错误,我只是重写t1:

class cclass extends t1 with t2 {

    override def printt1 = …
Run Code Online (Sandbox Code Playgroud)

inheritance scala mixins

1
推荐指数
1
解决办法
681
查看次数