小编drh*_*gen的帖子

Scala:当类型参数是成员类型时,集合的类型参数在"collect"中存活

通常,在收集与特定类型匹配的序列的所有元素时,生成的集合既具有原始集合的类型,又具有为以下类型选择的类型:

trait Foo
trait Bar

trait Baz {
  // Works
  def def1(foo: Seq[Foo]): Seq[Foo with Bar] = 
    foo collect {case foobar: Bar => foobar}
}
Run Code Online (Sandbox Code Playgroud)

当输入类型由有界成员类型参数化并且我想要的全部是由绑定类型(而不是成员类型)参数化的序列时,这甚至有效:

trait Baz {
  type memberType <: Foo

  // Works
  def2(foo: Seq[memberType]): Seq[Foo with Bar] =
    foo collect {case foobar: Bar => foobar}
}
Run Code Online (Sandbox Code Playgroud)

但是,当我真的想要返回由成员类型参数化的序列时,这会失败:

trait Baz {
  type memberType <: Foo

  // Fails
  def def3(foo: Seq[memberType]): Seq[memberType with Bar] =
    foo collect {case foobar: Bar => foobar}
}
Run Code Online (Sandbox Code Playgroud)

错误信息:

error: type mismatch;
 found   : …
Run Code Online (Sandbox Code Playgroud)

scala type-inference partialfunction type-parameter

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

R等价于Stata本地或全局宏

我是Stata用户,想要学习R.

我有几个冗长的文件夹路径,在我的Stata代码中,我存储为本地宏.我在这两个文件夹中有多个文件可供我的分析使用.

我知道,在R中,每次我想引用其中一个文件夹中的文件时,我都可以更改工作目录,但这绝对不是一个好方法.即使我将文件夹路径存储为R中的字符串,我也无法弄清楚如何引用它们.例如,在Stata中我会使用`folder1'.

我想知道是否尝试在R中逐行重写Stata代码并不是学习R的最佳方法.

有人可以帮忙吗?

r local stata stata-macros

5
推荐指数
2
解决办法
4437
查看次数

使用返回通用特征的方法实现特征

我正在尝试设计一对特征(例如RowVectorColumnVector来自线性代数),其中每个特征从其方法之一返回另一个特征(例如transpose)。我希望将来能够添加任一特征的实现(例如密集和稀疏向量实现)。

#[macro_use]
extern crate derive_new;

trait RowVector<Element> {
    fn transpose(self) -> ColumnVector<Element>;
}

trait ColumnVector<Element> {
    fn transpose(self) -> RowVector<Element>;
}

#[derive(new, Debug)]
struct VecRowVector<Element> {
    vec: Vec<Element>
}

#[derive(new, Debug)]
struct VecColumnVector<Element> {
    vec: Vec<Element>
}

impl<Element> RowVector<Element> for VecRowVector<Element> {
    fn transpose(self) -> VecColumnVector<Element> {
        VecColumnVector::new(self.vec)
    }
}

impl<Element> ColumnVector<Element> for VecColumnVector<Element> {
    fn transpose(self) -> VecRowVector<Element> {
        VecRowVector::new(self.vec)
    }
}

fn main() {
    let row_vector = VecRowVector::new(vec![1,2,3]);
    let col_vector = VecColumnVector::new(vec![1,2,3]); …
Run Code Online (Sandbox Code Playgroud)

generics traits rust

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

在包含数字和对象的数组上使用NumPy函数

我有相同数量级的,我已经实现了sqrt,exp等方法,使NumPy的功能将他们播出时,他们在ndarray秒.

class A:
    def sqrt(self):
        return 1.414
Run Code Online (Sandbox Code Playgroud)

这个工作完美地在这些:

import numpy as np
print(np.sqrt([A(), A()]))  # [1.414 1.414]
Run Code Online (Sandbox Code Playgroud)

显然,sqrt也适用于纯数字:

print(np.sqrt([4, 9]))  # [2. 3.]
Run Code Online (Sandbox Code Playgroud)

但是,当数字和对象混合时,这不起作用:

print(np.sqrt([4, A()]))

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-38-0c4201337685> in <module>()
----> 1 print(np.sqrt([4, A()]))

AttributeError: 'int' object has no attribute 'sqrt'
Run Code Online (Sandbox Code Playgroud)

发生这种情况是因为dtype异构数组是object通过在每个对象上调用同名方法来广播numpy函数,但是数字没有具有这些名称的方法.

我该如何解决这个问题?

python numpy

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

调用 WebSocket.close 时现有等待会发生什么

如果我打开 Starlette/FastAPI WebSocket,如果我从协程外部关闭 WebSocket,当前等待从客户端接收数据的协程会发生什么?是调用receive引发异常还是协程永远留在内存中,因为它永远不会收到任何东西?

from fastapi import FastAPI
from fastapi.websockets import WebSocket

app = FastAPI()

open_sockets = {}

@app.websocket('/connection/')
async def connection(websocket: WebSocket):
    await websocket.accept()

    id = await websocket.receive_json()['id']
    open_sockets[id] = websocket

    while True:
        data = await websocket.receive_json()

@app.post('/kill/{id}/')
async def kill(id=str):
    # What does this do to the above `await websocket.receive_json()`?
    await open_sockets[id].close()
    del open_sockets[id]
Run Code Online (Sandbox Code Playgroud)

python websocket python-asyncio starlette fastapi

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

Plotly:更改图例条目之间的空间?

如何减少 Plotly 中图例条目之间的间隔/间距?将图例字体变小只会产生如此大的影响。我想这样做是因为我的真实案例有很多条目,我需要压缩它们。

这是一个 Python Plotly Express 示例,但怀疑前端语言是否重要。请注意图例中“女性,否”、“女性,是”等之间的巨大空间:

import plotly.express as px

df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", color="sex", symbol="smoker", facet_col="time",
          labels={"sex": "Gender", "smoker": "Smokes"})

fig.update_layout(
    legend=dict(
        font=dict(
            size=6,
        ),
    )
)

fig.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

python plotly

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

停用所有 conda 环境

当激活 conda 环境时,conda 会记住之前激活的环境。例如,如果没有激活任何环境,则调用conda activate foo和 thenconda deactivate会导致没有任何环境处于活动状态。然而,调用conda activate foo, then conda activate bar, thenconda deactivate会导致“foo”环境处于活动状态。Conda 在激活每个环境时将其放入堆栈中,停用时只会从堆栈中弹出一项。

使用 bash 版本的 conda 时如何停用所有 conda 环境?

例如,如果我有一个重建环境的脚本,则需要确保该环境当前不处于活动状态,因此它应该停用所有环境。conda deactivate我可以在脚本顶部粘贴十个左右,这可能就足够了,但我正在寻找不那么糟糕的东西。

conda

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

在锡兰中打破多个for循环

假设我for在锡兰有几个嵌套循环.如何突破所有循环:

variable Integer? something = null;
for (i in 0:3) {
  for (j in 0:3) {
    for (k in 0:3) {
      something = someFunction(i,j,k);
      if (something exists) {
        // break out of everything, we found it
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

ceylon

4
推荐指数
2
解决办法
124
查看次数

当其中一个是本地引用时,如何在类型约束中编写引用的生存期?

我有一个特征Matrix和通用功能semi_def<T: Matrix>(x: &T),我想对该特征进行操作。该功能需要一个操作员特征,例如Mul,在上实现T。但是,如果引用之一是对局部变量的引用,我似乎无法使一生愉快。当其中之一只是本地临时引用时,如何在类型约束中编写引用的生存期?

use std::ops::Mul;

trait Matrix: Clone {
    fn transpose(self) -> Self;
}

#[derive(Clone)]
struct DenseMatrix {
    n_rows: usize,
    n_columns: usize,
    elements: Vec<f64>,
}

impl Matrix for DenseMatrix {
    fn transpose(self) -> Self {
        unimplemented!()
    }
}

impl<'a, 'b> Mul<&'b DenseMatrix> for &'a DenseMatrix {
    type Output = DenseMatrix;
    fn mul(self, _rhs: &'b DenseMatrix) -> Self::Output {
        unimplemented!()
    }
}

fn semi_def<'a, T: Matrix>(x: &'a T) -> T
where
    &'a T: …
Run Code Online (Sandbox Code Playgroud)

generics lifetime rust

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

设置matplotlib 3D绘图的刻度颜色

如果我有3D matplotlib图(Axes3D对象),如何更改刻度线的颜色?我想出了如何更改轴线,刻度标签和轴标签的颜色.显而易见的解决方案,使用ax.tick_params(axis='x', colors='red'),只更改刻度标签而不是刻度标记本身.

以下是尝试将所有轴更改为红色并获取除刻度标记之外的所有轴的代码:

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt

fig = plt.figure()
ax = Axes3D(fig)

ax.scatter((0, 0, 1), (0, 1, 0), (1, 0, 0))
ax.w_xaxis.line.set_color('red')
ax.w_yaxis.line.set_color('red')
ax.w_zaxis.line.set_color('red')
ax.w_zaxis.line.set_color('red')
ax.xaxis.label.set_color('red')
ax.yaxis.label.set_color('red')
ax.zaxis.label.set_color('red')
ax.tick_params(axis='x', colors='red')  # only affects
ax.tick_params(axis='y', colors='red')  # tick labels
ax.tick_params(axis='z', colors='red')  # not tick marks

fig.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

python matplotlib mplot3d

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