小编hel*_*low的帖子

从使用期货的套接字列表中选择

我正在尝试在夜间Rust 1.38中使用futures-preview = "0.3.0-alpha.16"和进行不稳定的async-await语法runtime = "0.3.0-alpha.6"。感觉真的很酷,但是文档还很稀缺,我被卡住了。

为了超越基本示例,我想创建一个应用程序:

  1. 在给定端口上接受TCP连接;
  2. 将从任何连接接收到的所有数据广播到所有活动连接。

现有的文档和示例使我到目前为止:

#![feature(async_await)]
#![feature(async_closure)]

use futures::{
    prelude::*,
    select,
    future::select_all,
    io::{ReadHalf, WriteHalf, Read},
};

use runtime::net::{TcpListener, TcpStream};

use std::io;

async fn read_stream(mut reader: ReadHalf<TcpStream>) -> (ReadHalf<TcpStream>, io::Result<Box<[u8]>>) {
    let mut buffer: Vec<u8> = vec![0; 1024];
    match reader.read(&mut buffer).await {
        Ok(len) => {
            buffer.truncate(len);
            (reader, Ok(buffer.into_boxed_slice()))
        },
        Err(err) => (reader, Err(err)),
    }
}

#[runtime::main]
async fn main() -> std::io::Result<()> {
    let mut listener = TcpListener::bind("127.0.0.1:8080")?;
    println!("Listening on {}", …
Run Code Online (Sandbox Code Playgroud)

rust async-await

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

将 svc 模型与 onevsallclassifier 结合使用时出现错误

from sklearn.multiclass import OneVsRestClassifier
from sklearn.svm import SVC

classifier = SVC(C=100, # penalty parameter, setting it to a larger value 
             kernel='rbf', # kernel type, rbf working fine here
             degree=3, # default value, not tuned yet
             gamma=1, # kernel coefficient, not tuned yet
             coef0=1, # change to 1 from default value of 0.0
             shrinking=True, # using shrinking heuristics
             tol=0.001, # stopping criterion tolerance 
             probability=False, # no need to enable probability estimates
             cache_size=200, # 200 MB cache size
             class_weight=None, # all classes …
Run Code Online (Sandbox Code Playgroud)

python-3.x scikit-learn

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

替换 RwLockWriteGuard 的内容

让我们假设以下代码:

use std::sync::RwLock;

pub struct NotCloneable(u8);

pub struct Foo {
    value: RwLock<Vec<NotCloneable>>,
}

impl Foo {
    // does not work
    pub fn filter_out_values(&self) {
        let mut guard = self.value.write().unwrap();
        *guard = guard.into_iter().filter(|nc| nc.0 != 0).collect();
    }
}
Run Code Online (Sandbox Code Playgroud)
use std::sync::RwLock;

pub struct NotCloneable(u8);

pub struct Foo {
    value: RwLock<Vec<NotCloneable>>,
}

impl Foo {
    // does not work
    pub fn filter_out_values(&self) {
        let mut guard = self.value.write().unwrap();
        *guard = guard.into_iter().filter(|nc| nc.0 != 0).collect();
    }
}
Run Code Online (Sandbox Code Playgroud)

操场

我如何使该功能filter_out_values正常工作?

rust

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

结构参考参数化函数的生命周期错误

如果我写下面的代码,我会得到error[E0309]: the parameter type 'T' may not live long enough.

struct Function<T> {
    f: fn() -> T,
}

struct FunctionRef<'f, T> {
    f: &'f Function<T>,
}
Run Code Online (Sandbox Code Playgroud)

这修复了错误:

struct FunctionRef<'f, T: 'f> {
    f: &'f Function<T>,
}
Run Code Online (Sandbox Code Playgroud)

但是,就我所知,T不受生命的束缚'f.实际上,是运行T类型函数时创建的新对象fn () -> T.

我在哪里错过了什么?

rust

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

如何限制结构的构造?

是否可以直接从成员初始化中禁止创建实例?

例如

pub struct Person {
    name: String,
    age: u8,
}

impl Person {
    pub fn new(age: u8, name: String) -> Person {
        if age < 18 {
            panic!("Can not create instance");
        }
        Person { age, name }
    }
}
Run Code Online (Sandbox Code Playgroud)

我仍然可以Person {age: 6, name:String::from("mike")}用来创建实例.反正有没有避免这个?

rust

6
推荐指数
2
解决办法
219
查看次数

如何使用 Diesel 在 sqlite 中存储任意 JSON 对象

我有一个输入 JSON:

{"key1": "val1", "key2": 1}
Run Code Online (Sandbox Code Playgroud)

我想将它存储在 sqlite 数据库中,以便稍后使用完全相同的值响应某些 API 请求。

这是我的迁移:

{"key1": "val1", "key2": 1}
Run Code Online (Sandbox Code Playgroud)

我的Cargo.toml

[package]
name = "diesel_playground"
version = "0.1.0"
authors = ["User <user@example.com>"]
edition = "2018"

[dependencies]
diesel = { version = "1.4" , features = ["sqlite"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
Run Code Online (Sandbox Code Playgroud)

使用以下代码:

CREATE TABLE my_table (
    id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    arbitrary_json TEXT NOT NULL
);
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

[package]
name = "diesel_playground" …
Run Code Online (Sandbox Code Playgroud)

rust rust-diesel

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

使用 From 特征触发将 u8 转换为枚举

我有这个代码:

#[derive(PartialEq, PartialOrd)]
enum ValueType {
    k1,
    k2,
    kUnknown,
}

impl ValueType {
    fn value(&self) -> u8 {
        match *self {
            ValueType::k1 => 0x0,
            ValueType::k2 => 0x1,
            ValueType::kUnknown => 0xff,
        }
    }
}

impl From<u8> for ValueType {
    fn from(orig: u8) -> Self {
        match orig {
            0x0 => return ValueType::k1,
            0x1 => return ValueType::k2,
            _ => return ValueType::kUnknown,
        };
    }
}

fn main() {
    let a: ValueType = 0x0 as u8; // error, expected enum `ValueType`, found u8
} …
Run Code Online (Sandbox Code Playgroud)

rust

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

使用Assembly.GetCallingAssembly()不返回调用程序集

在我的ASP.NET MVC应用程序中,我使用一个小助手来遍历所有控制器.这个帮助器位于与我的MVC应用程序不同的程序集中,我正在引用它.

问题是,当在helper中调用Assembly.GetCallingAssembly()方法时,它不会返回MVC app程序集,而是返回帮助程序集.这不是我期望得到的,因为我的所有控制器都存在于MVC app程序集中,我需要反映它.

视图代码(MVC app assembly):

<nav>
   <ul id="menu">
      @foreach(var item in new MvcHelper().GetControllerNames())
      {
         @Html.ActionMenuItem(
              (string)HttpContext.GetGlobalResourceObject("StringsResourse", item), "Index",
              item)
      }
   </ul>
</nav>
Run Code Online (Sandbox Code Playgroud)

帮助程序代码(独立程序集):

public class MvcHelper
{
    public  List<string> GetControllerNames()
    {
        var controllerNames = new List<string>();
        GetSubClasses<Controller>().ForEach(
            type => controllerNames.Add(type.Name));
        return controllerNames;
    }

    private static List<Type> GetSubClasses<T>()
    {
        return Assembly.GetCallingAssembly().GetTypes().Where(
            type => type.IsSubclassOf(typeof(T))).ToList();
    }
}
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?

c# reflection asp.net-mvc

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

Bash for 循环和全局扩展

考虑以下 bash 代码:

 for f in /tmp/*.dat; do echo ${f}; done
Run Code Online (Sandbox Code Playgroud)

当我运行它并且输出中没有*.dat文件时/tmp

/tmp/*.dat
Run Code Online (Sandbox Code Playgroud)

这显然不是我想要的。但是,当有这样的文件时,它会打印出正确的

/tmp/foo.dat
Run Code Online (Sandbox Code Playgroud)

当目录中没有这样的文件时,如何强制 for 循环返回“无”。该find-command是不是一种选择,对不起为:/我想也有一个解决方案,而测试中,如果*.dat是文件还是不行。到目前为止有任何解决方案吗?

bash

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

实现proc宏时循环依赖包

我尝试实现Dump类似于serdes的proc_macro Serialize

为了这个目的,我有一个箱子foo包含我的“原始”结构(P1P2在这种情况下),这应该只是dumpable。

接下来,我确实有一个foo_derive包含程序宏本身的板条箱。

因为我想支持多种格式,所以我有第三个板条箱foo_dump,其中包含trait定义Dump(例如,可以转储此结构)和Dumper(这是后端应实现的)。非常直截了当的到这一点。

现在,我想编译它时,出现以下错误:

$ cargo build
error: cyclic package dependency: package `foo v0.1.0 (/tmp/tmp.u34pI5J6qd/example/foo)` depends on itself. Cycle:
package `foo v0.1.0 (/tmp/tmp.u34pI5J6qd/example/foo)`
    ... which is depended on by `foo_dump v0.1.0 (/tmp/tmp.u34pI5J6qd/example/foo_dump)`
    ... which is depended on by `foo_derive v0.1.0 (/tmp/tmp.u34pI5J6qd/example/foo_derive)`
Run Code Online (Sandbox Code Playgroud)

我不知道正确的方法是什么,如何在此板条箱中使用依赖项。我当前的是:

依存关系

这当然是不可能的。

我想念什么?我该怎么做才能打破依赖圈?


mcve @ github

/Cargo.toml

[workspace]
members = [ 
    "foo",
    "foo_derive",
    "foo_dump",
]
Run Code Online (Sandbox Code Playgroud)

/foo/Cargo.toml

[package]
name …
Run Code Online (Sandbox Code Playgroud)

rust rust-macros rust-proc-macros

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