小编Ben*_*Ben的帖子

在函数内定义包含换行符的子字符串的三引号 f 字符串,且不输出缩进

我正在尝试漂亮地打印一个 HTTP 请求(我在这里嘲笑过)。

from typing import NamedTuple

class RequestMock(NamedTuple):
    method = 'POST'
    url = 'https://bob.com'
    body = 'body1\nbody2'
    headers = {'a': '1', 'b': '2'}
Run Code Online (Sandbox Code Playgroud)

我有一个函数可以执行此操作:

req = RequestMock()

def print1(req):
    headers = '\n'.join(f'{k}: {v}' for k, v in req.headers.items())
    s = '\n'.join([
        f'{req.method} {req.url}',
        headers,
        req.body
    ])
    print(s)

print1(req)
# POST https://bob.com
# a: 1
# b: 2
# body1
# body2
Run Code Online (Sandbox Code Playgroud)

f-strings但是,当我为了清晰和易于修改而尝试重写它时,我得到了一些不好的缩进:

# what I want the code to look like
def print2(req):
    headers = '\n'.join(f'{k}: {v}' for …
Run Code Online (Sandbox Code Playgroud)

python formatting f-string

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

删除 | 来自 Typescript 类型的 null

我刚开始学习 TypeScript,在某些情况下,我得到的可能是 Type 或 null。有没有一种优雅的方法来处理这些情况?

function useHTMLElement(item: HTMLElement) {
  console.log("it worked!")
}

let myCanvas = document.getElementById('point_file');
if (myCanvas == null) {
  // abort or do something to make it non-null
}
// now I know myCanvas is not null. But the type is still `HTMLElement | null`
// I want to pass it to functions that only accept HTMLElement.
// is there a good way to tell TypeScript that it's not null anymore?
useHTMLElement(myCanvas);
Run Code Online (Sandbox Code Playgroud)

我编写了以下似乎有效的函数,但这似乎是一个很常见的情况,我想知道语言本身是否为此提供了一些东西。

function ensureNonNull <T> (item: T …
Run Code Online (Sandbox Code Playgroud)

javascript error-handling null types typescript

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

如何使用智能指针进行自动清理?

我正在制作一个简单的日志类,其中包含指向 astd::ofstreamstd::cerr.

无论使用哪个流,是否有任何简单的方法可以使用智能指针进行自动清理?

代码必须在 clang++、g++ 和 VS2013 上编译。

代码

#include <iostream>
#include <fstream>
#include <string>

class Logger {
private:
    std::ostream * output_stream{ nullptr };
    bool using_file{ false };
public:
    Logger()
    {
        output_stream = &std::cerr;
        using_file = false;
    }
    Logger(std::string file)
    {
        output_stream = new std::ofstream(file);
        using_file = true;
    }
    ~Logger()
    {
        if (using_file)
        {
            delete output_stream;
        }
    }
    template<typename T>
    void log(T info)
    {
        *output_stream << info << std::endl;
    }
};

class tmp {
    int i{ …
Run Code Online (Sandbox Code Playgroud)

c++ pointers smart-pointers stream c++11

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

aiohttp 是否支持 HTTPS 代理

当我尝试通过 HTTPS 代理发出请求时 -

async with session.get(
    url
    headers={"k": v},
    proxy='https://my-proxy.com:1234',
) as response:
    resp_json = await response.json()
Run Code Online (Sandbox Code Playgroud)

我的请求失败,但出现以下异常:

raise ValueError("Only http proxies are supported")
Run Code Online (Sandbox Code Playgroud)

这对应于源代码

然而,文档说支持 HTTPS 代理。

这是文档中的疏忽还是我做错了?

python https proxy http-proxy aiohttp

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

如何使 Elm-UI 元素响应按“Enter”

当按下 Enter 时,我需要让我的应用程序发送一条消息。我有一个元素,如:

Input.text [] { onChange = UpdateText, text = model.text, placeholder=Nothing }
Run Code Online (Sandbox Code Playgroud)

按下回车键时如何使其提交?

注意:Q/A 从Elm-Slack复制以方便查找。

elm elm-ui

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

contextlib.redirect_stdout总是一个好主意吗?

由于我已经了解了这种模式,我一直在使用

with open('myfile.txt','w') as myfile:
    with contextlib.redirect_stdout(myfile):
        # stuff
        print(...) # gets redirected to file
Run Code Online (Sandbox Code Playgroud)

这让我可以使用打印语法(我更喜欢)写入文件,我可以轻松地将其注释掉以打印到屏幕进行调试.但是,通过这样做,我将删除写入文件和屏幕的能力,并可能编写不太清晰的代码.我应该知道还有其他任何缺点,这是我应该使用的模式吗?

python stdout file python-3.x

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

std :: vector在重新分配时不调用析构函数

我正在尝试使用a std::vector来保存一些S实例.但是,当我重新分配向量的成员时,不会在前一个租户上调用析构函数:

#include <iostream>
#include <vector>

struct S {
    int index_;
    S(int index) : index_(index) {
        std::cout << "Calling S " << index_ << " constructor\n";
    }
    S(const S& other) : index_(other.index_) {
        std::cout << "Calling S " << index_ << " copy constructor\n";
    }
    ~S() {
        std::cout << "Calling S " << index_ << " destructor\n";
    }
};


int main()
{
    std::vector<S> v;
    v.reserve(10); // Let's not worry about copy constructors
    std::cout << "# Created …
Run Code Online (Sandbox Code Playgroud)

c++ memory destructor vector

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