小编jba*_*ter的帖子

fetch:使用JSON错误对象拒绝承诺

我有一个HTTP API,它在成功和失败时返回JSON数据.

示例失败将如下所示:

~ ? http get http://localhost:5000/api/isbn/2266202022 
HTTP/1.1 400 BAD REQUEST
Content-Length: 171
Content-Type: application/json
Server: TornadoServer/4.0

{
    "message": "There was an issue with at least some of the supplied values.", 
    "payload": {
        "isbn": "Could not find match for ISBN."
    }, 
    "type": "validation"
}
Run Code Online (Sandbox Code Playgroud)

我想在JavaScript代码中实现的是这样的:

fetch(url)
  .then((resp) => {
     if (resp.status >= 200 && resp.status < 300) {
       return resp.json();
     } else {
       // This does not work, since the Promise returned by `json()` is never fulfilled
       return Promise.reject(resp.json()); …
Run Code Online (Sandbox Code Playgroud)

javascript promise es6-promise fetch-api

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

SQLAlchemy:声明性Mixin类中的getter/setter

我正在尝试为我打算在我的数据库模式中使用的mixin类定义简单的getter/setter方法:

from sqlalchemy import Column, Integer, create_engine
from sqlalchemy.orm import synonym, scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base, declared_attr

engine = create_engine('sqlite:///')
Base = declarative_base(bind=engine)
Session = scoped_session(sessionmaker(bind=engine))


class Mixin(object):
    _attr = Column('attr', Integer)

    @property
    def attr(self):
        return self._attr

    @attr.setter
    def attr(self, value):
        self._attr = value

    attr = synonym('_attr', descriptor=attr)


class DummyClass(Base, Mixin):
    __tablename__ = 'dummy'

    id = Column(Integer, primary_key=True)

Base.metadata.create_all()

if __name__ == '__main__':
    session = Session()
    testobj = DummyClass()
    session.add(testobj)
    testobj.attr = 42
    assert testobj.attr == 42
Run Code Online (Sandbox Code Playgroud)

当我尝试运行此示例时,我收到以下错误:

sqlalchemy.exc.InvalidRequestError:Mapper属性(即deferred,column_property(),relationship()等)必须在声明性mixin类中声明为@declared_attr …

python sqlalchemy

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

Android:在自定义WebView中从onLongPress打开ContextMenu

我目前正在尝试获取一个自定义WebView,当它被按下较长时间时会显示一个ContextMenu.由于默认WebView类仅在链接为longPressed时显示ContextMenu,因此我编写了自己的类来覆盖此行为:

public class MyWebView extends WebView {
    Context context;
    GestureDetector gd;

    public MyWebView(Context context, AttributeSet attributes) {
        super(context, attributes);
        this.context = context;
        gd = new GestureDetector(context, sogl);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return gd.onTouchEvent(event);
    }

    GestureDetector.SimpleOnGestureListener sogl =
                new GestureDetector.SimpleOnGestureListener() {

        public boolean onDown(MotionEvent event) {
            return true;
        }

        public void onLongPress(MotionEvent event) {
            // The ContextMenu should probably be called here
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

这可以正常工作,检测到longPress并调用onLongPress方法,但是在显示ContextMenu时我不知所措.我尝试在我的Activity中按照惯例进行操作:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout);

    MyWebView mwv = (MyWebView) …
Run Code Online (Sandbox Code Playgroud)

android contextmenu webview gesturedetector

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

SQLAlchemy:具有动态'association_proxy'创建函数的多重继承

我目前正在尝试使用SQLAlchemy创建以下数据库模式(使用ext.declarative):

我有一个基类MyBaseClass,它为我所有可公开访问的类提供了一些常用功能,这是一个mixin类MetadataMixin,它提供了从imdb查询元数据并存储它的功能.子类的每个类MetadataMixin都有一个字段persons,它提供与Person类实例的M:N关系,以及一个persons_roles提供1:N关系的字段(一个用于每个子类),它存储role一个具体的人在一个实例中播放子类.

这是我的代码目前的缩写版本:

from sqlalchemy import Column, Integer, Enum, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class MyBaseClass(object):
    """Base class for all publicly accessible classes"""
    id = Column(Integer, primary_key=True)


class Person(MyBaseClass):
    """A Person"""

    name = Column(Unicode)
    movies = association_proxy('movie_roles', 'movie',
                               creator=lambda m: _PersonMovieRole(movie=m))
    shows = association_proxy('show_roles', 'show',
                              creator=lambda s: _PersonShowRole(show=s=))


class _PersonMovieRole(Base):
    """Role for a Person in …
Run Code Online (Sandbox Code Playgroud)

python sqlalchemy multiple-inheritance

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

如何通过编译器选项覆盖常量?

是否可以在源代码中定义一个可以被编译器标志覆盖的常量?也就是说,类似#define在C预处理器中设置带有-D key=val编译器选项的值。

我已经阅读了有关通过#[cfg(...)]属性进行条件编译的信息,但这似乎仅支持布尔值。我想允许用户在编译期间设置常量的值。

像这样:

#[from_cfg("max_dimensions")]
const MAX_DIMENSIONS: usize = 100_000;
Run Code Online (Sandbox Code Playgroud)

rust

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

在win32下对stdin使用fread()的问题

我试图在Win32下以二进制模式解析stdin中的数据.我的代码所做的第一件事就是在开头检查一个4byte的头:

int riff_header;
fread(&riff_header, sizeof(riff_header), 1, ifp);
//  'RIFF' = little-endian
if (riff_header != 0x46464952) {
    fprintf(stderr, "wav2msu: Incorrect header: Invalid format or endianness\n");
    fprintf(stderr, "         Value was: 0x%x\n", riff_header);
    return -1;
}
Run Code Online (Sandbox Code Playgroud)

stdin 在读取之前已经切换到二进制模式:

if (*argv[argc-1] == '-') {
    fprintf(stderr, "Reading from stdin.\n");
    infile = stdin;
    // We need to switch stdin to binary mode, or else we run
    // into problems under Windows
    freopen(NULL, "rb", stdin);
}
Run Code Online (Sandbox Code Playgroud)

这段代码在Linux下工作正常,但是在Win32(特别是Windows XP)上,fread似乎只能读取单个字节,从而导致评估失败.例:

> ffmeg.exe -i ..\test.mp3 -f wav pipe:1 …
Run Code Online (Sandbox Code Playgroud)

c windows pipe stdio

3
推荐指数
2
解决办法
2815
查看次数

Java正则表达式:将子串与新行匹配,后跟空格

我目前正试图通过将它们与正则表达式匹配来从字符串中提取子字符串.输入字符串都是以形式存在的foo.bar("""foobar"""),其中foobar是我想要提取的子字符串.这是我为此任务编写的正则表达式:

Pattern pattern = Pattern.compile(
            ".+\\(\"{3}(.+)\"{3}\\)" , Pattern.MULTILINE);
Run Code Online (Sandbox Code Playgroud)

它与简单的字符串很好地匹配,但是只要在要匹配的字符串中出现换行后跟空格,即失败 foo.bar("""foo\n bar""")

我如何更改我的模式以便它也匹配这些字符串?

java regex whitespace newline

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