小编swd*_*don的帖子

在 Golang 中将 JSON 中的字符串解析为枚举

我有一个枚举定义为

type MyEnum int

const(
   FirstEnum MyEnum = iota
)
Run Code Online (Sandbox Code Playgroud)

然后,我有一个包含键值对的 json "Key": "FirstEnum"。我就是这样解组的。

var data map[string]interface{}
err := json.Unmarshal([]byte(json), &data)
x := data["key"].(MyEnum)
Run Code Online (Sandbox Code Playgroud)

但是,当我运行此命令时,我收到错误:

panic: interface conversion: interface {} is string, not ps.Protocol [recovered]
        panic: interface conversion: interface {} is string, not ps.Protocol
Run Code Online (Sandbox Code Playgroud)

有没有办法让它像 Go 中枚举的字符串表示形式到枚举类型的正常转换一样工作?

enums json go unmarshalling

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

多个应用程序的 Django Rest Framework URL 映射

我有一个名为 django-rest 的项目main,在它下我创建了一个名为 的应用程序users。所以,我的项目有这些文件:-

主/主/urls.py

主/用户/urls.py

在 users/urls.py 我有

from django.conf.urls import url, include
from rest_framework import routers
from users import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
Run Code Online (Sandbox Code Playgroud)

在 main/main/urls.py 中我有

from django.conf.urls import url
from django.contrib import admin

from users import urls

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^users/', users.urls),
]
Run Code Online (Sandbox Code Playgroud)

但是,我不断收到错误NameError: name 'users' is not defined。当我有多个应用程序时,设置 url 的正确方法是什么?我希望为每个独立于项目的应用程序都有一个 urls.py 文件。在根 urls.py 中将包含到不同应用程序的路由。

django django-rest-framework

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

Azure DevOps:资产文件没有“.NETCoreApp,Version=v2.2/linux-x64”的目标

我正在使用任务组在 Azure DevOps 中为 AspNet Core Web Api 创建一个构建管道,该任务组首先安装 .Net Core SDK (2.2),然后使用dotnet restore(使用 VSTS 源)进行包还原,然后构建项目。

在构建步骤,我提供以下参数:

--configuration Release --runtime $(Target Platform) --no-restore /p:Version=$(Major Version).$(Minor Version).$(Build.BuildNumber).

buildstep 的所有步骤都成功了。但是,我在构建步骤中收到以下错误:

[command]C:\windows\system32\chcp.com 65001
Active code page: 65001
[command]C:\hostedtoolcache\windows\dotnet\dotnet.exe build D:\a\1\s\WebApp\WebApp.csproj --configuration Release --runtime linux-x64 --no-restore /p:Version=1.0.40
Microsoft (R) Build Engine version 16.2.32702+c4012a063 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

C:\hostedtoolcache\windows\dotnet\sdk\2.2.401\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets(208,5): error NETSDK1047: Assets file 'D:\a\1\s\WebApp\obj\project.assets.json' doesn't have a target for '.NETCoreApp,Version=v2.2/linux-x64'. Ensure that restore has …
Run Code Online (Sandbox Code Playgroud)

nuget-package-restore azure-devops azure-pipelines-release-pipeline

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

如何将 CMAKE_MAKE_PROGRAM 设置为 Ninja?

我是 CMake 的新手,正在尝试了解如何配置 CMake 以使用 Ninja 作为构建工具。我遇到的具体问题是我正在尝试使用他们的 install.py 安装 Vim 的 YouCompleteMe 插件。我收到以下错误:

Searching Python 3.8 libraries...
Found Python library: /usr/lib64/libpython3.8.so
Found Python headers folder: /usr/include/python3.8
CMake Error: CMake was unable to find a build program corresponding to "Unix Makefiles".  CMAKE_MAKE_PROGRAM is not set.  You probably need to select a different build tool.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "/tmp/ycm_build__dy3xdvd/CMakeFiles/CMakeOutput.log".
ERROR: the build failed.
Run Code Online (Sandbox Code Playgroud)

在互联网上查找类似错误后,我意识到可以通过安装 …

makefile cmake ninja

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

如何使用Comparer初始化嵌套的Sorted Dictionary?

我想创建一个排序字典的字典,其中排序的字典按降序排列键.我想尝试:

private readonly IDictionary<string, SortedDictionary<long, string>> myDict= new Dictionary<string, SortedDictionary<long, string>>();
Run Code Online (Sandbox Code Playgroud)

如何设置比较器如:

Comparer<long>.Create((x, y) => y.CompareTo(x))
Run Code Online (Sandbox Code Playgroud)

对于嵌套字典?

.net c# asp.net-core-2.1

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

用于 asp.net core 的 NLog 不过滤 Microsoft 日志

我在 ASP.NET Core 2.1 项目中有以下nlog.config文件。但是,它将来自每个记录器(包括 Microsoft 记录器)的消息记录到控制台。

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Error"
      internalLogFile="${specialfolder:folder=UserProfile}\nlog\internal-nlog.txt">

  <variable name="fullLayout" value="${shortdate}  [${uppercase:${level}}]  ${logger}: ${message}  ${exception:format=tostring}  url: ${aspnet-request-url}" />

  <!-- enable asp.net core layout renderers -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <!-- the targets to write to -->
  <targets>
    <!-- write to console -->
    <target name="console" xsi:type="ColoredConsole" layout="${fullLayout}" />

    <!-- write to file -->
    <target xsi:type="File"
            name="allfile"
            fileName="${defaultDirectory}/test-api-all.log"
            archiveEvery="Day"
            archiveFileName="${defaultDirectory}/test-api-all-${#}.log"
            archiveNumbering="Date"
            archiveDateFormat="yyyy-MM-dd"
            maxArchiveFiles="5"
            layout="${fullLayout}" />

    <!-- another file log, only own …
Run Code Online (Sandbox Code Playgroud)

c# nlog asp.net-core-2.1

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

EF Core 未引发 ValidationException

我有一个DbContext像这样的基类

public abstract class DbContextBase : DbContext
{
    public DbContextBase()
    {
    }

    public DbContextBase(DbContextOptions options)
        : base(options)
    {
    }

    public override int SaveChanges()
    {
        this.ValidateEntities();

        return base.SaveChanges();
    }

    public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
    {
        this.ValidateEntities();

        return base.SaveChangesAsync(cancellationToken);
    }

     public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
     {
        this.ValidateEntities();

        return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
    }

    protected virtual void ValidateEntities()
    {
        var entities = this.ChangeTracker.Entries().
                            Where(s => s.State == EntityState.Added || s.State == EntityState.Modified);

        foreach (var entity in entities) …
Run Code Online (Sandbox Code Playgroud)

c# model-validation asp.net-core-webapi ef-core-2.1

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

如何使用 EF Core fluent api 创建多个索引?

奇怪的是,我在任何地方都找不到任何例子或提及此事。我想使用 fluent api 在我的两个列上设置索引(不是复合索引,只是两个单独的索引)。

例如,我想知道是否可以执行以下操作:

modelBuilder.Entity<T>
            .HasIndex(h => h.Column1)
            .HasIndex(h => h.Column2);
Run Code Online (Sandbox Code Playgroud)

但是,从它的外观来看,不可能像这样链接索引。目前我正在做的是分别设置它们,如:

modelBuilder.Entity<T>
            .HasIndex(h => h.Column1)

modelBuilder.Entity<T>
            .HasIndex(h => h.Column2)
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?

c# ef-core-2.1

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

使用 Moq 验证在单独的线程/线程池中发生的方法调用

我之前已经成功设置并验证了 Moq 的方法,但不知何故我无法让它工作。我对同一个例外尝试了各种答案,但没有运气。

我已经实现了观察者模式,所以我在嘲笑IObserver<T>

var mock = new Mock<IObserver<T>>();
mock.Setup(s => s.OnCompleted());
Run Code Online (Sandbox Code Playgroud)

这里OnCompleted()看起来像

public void OnCompleted()
{
}
Run Code Online (Sandbox Code Playgroud)

现在在测试中,使用mock,我确实喜欢这样:

// observable is the SUT.
var unsubscriber = observable.Subscribe(mock.Object);
// Cause OnCompleted() to be called: I verified that there's one observer in the observers list in observable and that my break point is correctly hit.

mock.Verify(v => v.OnCompleted(), Times.AtLeastOnce);
unsubscriber.Dispose(); 
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Message: Moq.MockException : 
Expected invocation on the mock at least once, but was never …
Run Code Online (Sandbox Code Playgroud)

c# moq

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

使用 CMake 和 Visual Studio 出现“无法解析的外部符号”错误

我正在尝试使用 CMake 在 Windows 上使用 Allegro5。我的“CMakeLists.txt”文件是

cmake_minimum_required (VERSION 3.8)

project("My Project")

set(SOURCE_FILES "main.cpp")
add_executable(core ${SOURCE_FILES})

set(ALLEGRO_INCLUDE ".\\dependencies\\allegro\\include")
set(ALLEGRO_LIB ".\\dependencies\\allegro\\lib")
set(ALLEGRO_DYLIB ".\\dependencies\\allegro\\bin\\*.dll")

include_directories(${ALLEGRO_INCLUDE})
link_directories(${ALLEGRO_LIB})
file(GLOB LIBRARIES ${ALLEGRO_DYLIB})

target_link_libraries(core ${LIBRARIES} ${ALLEGRO_DYLIB})
Run Code Online (Sandbox Code Playgroud)

我的目录结构是:

root
|--CMakeLists.txt
|--main.cpp
|--build # this is where VS project files are generated.
|--dependencies
      |--allegro
           |--include
           |--lib
           |--bin
Run Code Online (Sandbox Code Playgroud)

我的main.cpp

#include <iostream>
#include <allegro5/allegro.h>

int main(int argc, char *args[])
{
    const int SCREEN_WIDTH = 640;
    const int SCREEN_HEIGHT = 480;

    ALLEGRO_DISPLAY *window = al_create_display(SCREEN_WIDTH, SCREEN_HEIGHT);
    std::system("pause");
    return 0;
} …
Run Code Online (Sandbox Code Playgroud)

c++ windows cmake allegro5 visual-studio-2017

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