AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题

全部问题(coding)

Martin Hope
Vroum
Asked: 2025-04-30 16:37:00 +0800 CST

ASP.NET WEB API 更改响应中的 JSON,因为它应该返回

  • 5

所以我目前正在用 .net5 构建一个 ASP.NET WEB API(我在一家公司实习,不幸的是我们只有 .net5 应用程序)。

简而言之,我的数据库中有一个“Component”表,其中包含一个 JSON 属性“Details”,EF Core 将其作为字符串导入到我的模型中。这没问题,我在我的模型中创建了另一个属性,ComponentDTO用于将字符串解析为实际的 JSON 值。

public partial class Component
{
    [...]
    public string Details { get; set; }
    [...]
}
public class ComponentDTO
{
    [...]
    public string Details { get; set; }
    public JObject ParsedDetails { get; set; }
}

我知道它以正确的方式解析,因为我捕获了应该在我的 API 函数内发送的 JSON,如下所示(电路板有组件):

[HttpGet("{Ref}")]
public async Task<ActionResult<IEnumerable<Board>>> Get(string Ref)
{
    try
    {
        var board = await _boardService.GetOneBoard(Ref);

        if (board == null)
        {
            return NotFound();
        }
        Console.WriteLine(board.Compositions.ElementAt(3).Component.ParsedDetails);

        var responseBody = JsonConvert.SerializeObject(board, Formatting.Indented);
        _logger.LogInformation($"Response: {responseBody}");

        return Ok(board);
    }
    catch(Exception e)
    {
        Console.WriteLine(e.Message);
        return StatusCode(500, "Internal Server Error");
    }
}

因此,当我记录响应主体时,我得到的是一个组件的详细信息:

"ParsedDetails": {
    "core": "Cortex-A53",
    "speed": "1.2 GHz",
    "memory_interface": "DDR3/4"
}

但在 Swagger 或我的浏览器中,这是我对同一组件获得的结果:

"parsedDetails": {
    "core": [],
    "speed": [],
    "memory_interface": []
}

这是我解析 JSON 属性的方式:

public static JObject ParseJsonDetails(string jsonString)
{
    JObject parsedDetails = string.IsNullOrEmpty(jsonString) ? new JObject() : JObject.Parse(jsonString);
    Console.WriteLine(parsedDetails);
    return parsedDetails;
}

public async Task<BoardDTO> GetOneBoard(string reference)
{
    return await _context.Boards
        .Select(b => new BoardDTO
        {
            [...]
            Compositions = b.Compositions.Select(c => new CompositionDTO
            {
                Component = new ComponentDTO
                {
                    [...]
                    ParsedDetails = ParseJsonDetails(c.Component.Details),
                }
            }).ToList(),
            [...]
        })
        .FirstOrDefaultAsync(b => b.Ref == reference);
}

我实际上不知道该怎么做,因为我在发送响应主体之前就捕获了它,而且我不知道该Ok(board)值是如何处理的,也没有引发任何异常或错误。

c#
  • 1 个回答
  • 33 Views
Martin Hope
Whirlwind
Asked: 2025-04-30 16:20:06 +0800 CST

当上下文保存设置为自动时,“modelContext.save()”有意义吗?

  • 6

由于它提供的便利之一SwiftData是在模型上下文中添加或更改某些内容时自动保存记录,那么显式调用save()会有什么区别吗?我想在两种情况下,SwiftData都会决定吗?

@ModelActor
public actor DataHandler {
    @discardableResult
    public func new(item: Item) throws -> PersistentIdentifier {
      modelContext.insert(item)
      try modelContext.save()
      return item.persistentModelID
    }
    
  @discardableResult
  public func newEmptyItem() throws -> PersistentIdentifier {
    let item = Item()
    modelContext.insert(item)
    try modelContext.save()
    return item.persistentModelID
  }

我可以删除这一行吗:

try modelContext.save()

不用担心?

swift
  • 2 个回答
  • 35 Views
Martin Hope
Mou Biswas
Asked: 2025-04-30 16:07:57 +0800 CST

如何将一个容器放置在另一个容器上 - Flutter

  • 5

我正在尝试为登录页面做这个特殊的设计。

用户界面

但我得到的结果如下:

在此处输入图片描述

我尝试的代码是:

               Stack(
                      fit: StackFit.passthrough,
                      children: [
                        Container(height: 2, color: Colors.grey),
                        Positioned(
                          child: Center(
                            child: Transform.rotate(
                              alignment: Alignment.center,
                              angle: 45,
                              child: Container(
                                height: 18,
                                width: 18,
                                color: colorController.primaryColor.value,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
flutter
  • 2 个回答
  • 27 Views
Martin Hope
Manish
Asked: 2025-04-30 15:33:17 +0800 CST

Laravel Auth::attempt() 错误:使用自定义密码字段时出现“未知列‘密码’”

  • 5

我正在开发一个 Laravel 项目,将项目从 codeigniter 迁移到 laravel,因此我使用多重防护身份验证和自定义管理员用户表,名为 tbl_admin_user,其中电子邮件和密码列均名为 admin_user_email_id 和 admin_user_password,而不是默认密码。

但目前我遇到了这个错误——我猜是字段名称没有映射,而且我不知道为什么它甚至能通过更新查询,而且哈希密码与我数据库中的密码不相似。这个错误在 attempt() 方法中突出显示。 错误

我有一个自定义的守卫管理员和一个自定义的 Office 模型,它们扩展了 Authenticatable。以下是我所做的 :


namespace App\Models;

use Illuminate\Support\Facades\Hash;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Office extends Authenticatable
{

    use HasFactory, Notifiable;

    protected $table = 'tbl_admin_user';
    protected $primaryKey = 'admin_user_id';
    public $incrementing = true;
    public $keyType = 'int';

    protected $fillable = [
        // other column names
        'admin_user_email_id',
        'admin_user_password',
       // other column names
        'admin_updated_on',
        'admin_created_on',
    ];

    // Use customized field name
    public function getAuthIdentifierName() {
        return 'admin_user_email_id';
    }
    
    // Gets the hashed password
    public function getAuthPassword() {
        return $this->admin_user_password;
    }


    public $timestamps = false;

}

控制器的登录功能

// Begin::Authenticate login
    public function authenticateOfficeLogin(Request $request) {
        // validate
        $validate = $request->validate([
            'admin_user_email_id' => 'required|email',
            'admin_user_password' => 'required'
        ]);
        
        // Store credentials
        $credentials = [
           'admin_user_email_id' => $validate['admin_user_email_id'],
           'password' => $validate['admin_user_password'],
           'admin_user_status' => 1,
        ];
        
        $user = Office::where('admin_user_email_id', $request->admin_user_email_id)->first(); // Gets the matching data

       
        // Check if user is authenticated
        if($user) {
            $authenticate = Auth::guard('admin')->attempt($credentials); // Here i got the error
            // if authenticated
                if($authenticate) {
                    return redirect()->route('office.dashboard')->with('success','Logged In Successfully!'); // redirect to the dashboard
                }
            }
        }
    // End::Authenticate login

我尝试过的方法:使用 php artisan config:clear、route:clear 和 cache:clear 清除配置和路由缓存,甚至尝试优化:clear。

在 Auth::attempt() 调用之前添加了 Log::info() 语句,但未记录任何内容。

在 attempt() 调用之前,使用 dd() 中的 Hash::check() 验证提供的密码是否与散列密码匹配,现在它返回 true。

  • 1 个回答
  • 36 Views
Martin Hope
Anurag Nema
Asked: 2025-04-30 14:22:00 +0800 CST

Angular 测试用例失败,错误代码为 NG0203:必须从注入上下文中调用 inject()

  • 6

我正在使用 TestBed 测试一个 Angular 18 独立组件,并在单元测试期间初始化组件时遇到此错误:错误:NG0203:必须从注入上下文(例如构造函数、工厂函数、字段初始化器或与 一起使用的函数)调用 inject() runInInjectionContext。更多信息请访问https://angular.dev/errors/NG0203

以下是该组件的测试用例:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SomeComponent } from './some-component.component';
import { ActivatedRoute } from '@angular/router';
import { of } from 'rxjs';

describe('SomeComponent', () => {
  let component: SomeComponent;
  let fixture: ComponentFixture<SomeComponent>;
  let mockRoute: jasmine.SpyObj<ActivatedRoute>;

  beforeEach(async () => {
    mockRoute = jasmine.createSpyObj('ActivatedRoute', ['fragment'], { fragment: of('test-anchor') });

    await TestBed.configureTestingModule({
      imports: [SomeComponent], 
      providers: [{ provide: ActivatedRoute, useValue: mockRoute }],
    }).compileComponents();

    fixture = TestBed.createComponent(SomeComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

组件代码:

import { Component, OnDestroy } from '@angular/core';
import { LibCommonService, PLATFORM_BEHAVIOR_TYPE_ENUM, PreferencesDashboardComponent } from '@pseudoLib/pseudo-common-elements';
import { TranslateModule } from '@ngx-translate/core';
import { ActivatedRoute } from '@angular/router';
import { Subject, takeUntil } from 'rxjs';
import { NgIf } from '@angular/common';
import { DetailsService } from 'src/shared/services/details.service';
import { MEMBER_TYPE_ENUM } from 'src/shared/models/enums/details.enum';

@Component({
  selector: 'app-some',
  standalone: true,
  imports: [TranslateModule, NgIf, PreferencesDashboardComponent],
  templateUrl: './some.component.html',
  styleUrl: './some.component.scss',
})
export class SomeComponent implements OnDestroy {
  private destroy$ = new Subject<void>();

  PLATFORM_BEHAVIOR_TYPE_ENUM = PLATFORM_BEHAVIOR_TYPE_ENUM;

  projectId!: string;

  memberId!: string;

  memberType!: PLATFORM_BEHAVIOR_TYPE_ENUM;

  constructor(
    private activatedRoute: ActivatedRoute,
    private libCommonService: LibCommonService,
    private DetailsService: DetailsService,
  ) {
    this.projectId = this.libCommonService.projectIdBehaviorSub.getValue();
    this.activatedRoute.parent?.params?.pipe(takeUntil(this.destroy$)).subscribe((params) => {
      this.memberId = params.id;
    });
    this.DetailsService.memberDetails$.pipe(takeUntil(this.destroy$)).subscribe(async (memberDetails) => {
      if (memberDetails?.memberType === MEMBER_TYPE_ENUM.PRIMARY) {
        this.memberType = PLATFORM_BEHAVIOR_TYPE_ENUM.PRIMARY_MEMBER;
      } else if (memberDetails?.memberType === MEMBER_TYPE_ENUM.ASSOCIATE) {
        this.memberType = PLATFORM_BEHAVIOR_TYPE_ENUM.ASSOCIATE_MEMBER;
      }
    });
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
}

如何解决测试环境中的 NG0203: inject() 错误?如有任何关于如何正确配置使用此服务的独立组件测试环境的建议,我们将不胜感激。

Angular 版本: Angular 18

angular
  • 1 个回答
  • 54 Views
Martin Hope
rochitsen
Asked: 2025-04-30 13:52:06 +0800 CST

使用 CommandParameter 设置属性时,不会保留类属性值

  • 6

CommandParameter我在 .net maui 9 中有一个下面的小例子,其中我通过在视图中单击按钮时设置的值来设置视图模型中的属性。

然后将此属性用作视图的属性BindingContext。因此,单击按钮时应显示的文本为。PlaceHolderTextEntryEntrySet PropertyOneText from Property

查看以下代码:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiBindingExample.MainPage"
             xmlns:local="clr-namespace:MauiBindingExample.ViewModels">

    <ScrollView>
        <VerticalStackLayout 
            Padding="30,0"
            Spacing="25">
            <Image
                Source="dotnet_bot.png"
                HeightRequest="185"
                Aspect="AspectFit"
                SemanticProperties.Description="dot net bot in a hovercraft number nine" />
            <Button
                BindingContext="{local:ExampleViewModel}"
                x:DataType="local:ExampleViewModel"
                Text="Set PropertyOne" 
                Command="{Binding SetPropertyOneCommand}"
                CommandParameter="Text from Property"/>
            <Entry
                BindingContext="{local:ExampleViewModel}"
                x:DataType="local:ExampleViewModel"
                PlaceholderColor="AliceBlue"
                Placeholder="{Binding EntryPlaceholderText}"/>
        </VerticalStackLayout>
    </ScrollView>
</ContentPage>

视图模型的代码如下:

using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;

namespace MauiBindingExample.ViewModels
{
    public class ExampleViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private string entryPlaceholderText;

        public string EntryPlaceholderText
        {
            get => entryPlaceholderText;
            set
            {
                entryPlaceholderText = value;
                OnPropertyChanged();
            }
        }
        
        public ICommand SetPropertyOneCommand { get; set; }

        public ExampleViewModel()
        {
            SetPropertyOneCommand = new Command<string>(
                (string arg) =>
                {
                    EntryPlaceholderText = arg;
                });
        }
        public void OnPropertyChanged([CallerMemberName] string propertyName="")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

当我设置调试器时,我可以确认单击按钮时属性EntryPlaceholderText设置正确Set PropertyOne,但是在命令执行完成后,属性EntryPlaceholderText被重置,因此没有Entry显示占位符文本。

可能存在什么问题?

非常感谢您的帮助。

maui
  • 1 个回答
  • 42 Views
Martin Hope
saromba
Asked: 2025-04-30 13:49:26 +0800 CST

带有 nginx 的 FastAPI 应用程序 - StaticFiles 不起作用

  • 6

我有一个简单的 FastAPI 项目。它在 Pycharm 和 Docker 容器中运行正常。但通过 nginx 运行时,StaticFiles无法交付。

结构是这样的:

├── app
│   ├── main.py
│   ├── static_stuff
│   │   └── styles.css
│   └── templates
│       └── item.html
├── Dockerfile
├── requirements.txt

主程序

from fastapi import Request, FastAPI
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import os.path as path


ROOT_PATH =  path.abspath(path.join(__file__ ,"../"))

app = FastAPI(title="my_app", root_path='/my_app')
app.mount("/static_stuff", StaticFiles(directory=f"/{ROOT_PATH}/static_stuff"), name="static")
templates = Jinja2Templates(directory=f"/{ROOT_PATH}/templates")


@app.get("/items/{id}", response_class=HTMLResponse, include_in_schema=False)
async def read_item(request: Request, id: str):
    return templates.TemplateResponse(
        request=request, name="item.html", context={"id": id}
    )

该应用程序正在docker容器中运行:

Dockerfile:

FROM python:3.13-slim
WORKDIR /my_app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY app ./app
CMD ["gunicorn",  "-k",  "uvicorn.workers.UvicornWorker", "app.main:app", "--bind",  "0.0.0.0:6543"]

EXPOSE 6543

nginx 配置如下:

location /my_app {
    proxy_pass        http://my_host:6543;
    include           proxy_params;
}

当调用 nginx -> http://my_host/my_app/items/5

除了静态文件之外,一切正常。找不到styles.css。我做错了什么?

我尝试过类似的方法,但没有成功

location ~ /static_stuff/(.+) {
    proxy_pass        http://my_host:6543;
    include           proxy_params;
}
python
  • 2 个回答
  • 51 Views
Martin Hope
rasmusrj
Asked: 2025-04-30 13:45:19 +0800 CST

Number(“NaN”) 是否返回 NaN,因为 js 将“NaN”识别为数字类型的值,或者因为它是一个字符串而不是数字?

  • 7

例如Number("Infinity")返回,Infinity因为它将其识别为数字类型,所以我想知道Number("NaN")返回是否出于与返回NaN相同的原因,还是因为它将其识别为数字,就像“无穷大”一样?Number("potato")NaN

javascript
  • 1 个回答
  • 126 Views
Martin Hope
Mariah Wedel
Asked: 2025-04-30 10:14:58 +0800 CST

为什么我会收到这个终端错误以及如何修复它?

  • 5

我在 VS Code 终端上使用 npm 时一直出现这个错误。有人知道为什么一直出现这个错误吗 ?

我尝试卸载并重新安装该节点,它说它正在运行正确的节点,没有问题,但是当我输入 npm install 时,出现此错误。

visual-studio
  • 1 个回答
  • 31 Views
Martin Hope
mr.questions
Asked: 2025-04-30 10:14:52 +0800 CST

ineq 包中的 Gini() 使用什么公式来获取 R 中的基尼系数?

  • 7

我正在写一篇论文,我想声明如何使用 ineq 包中的 Gini() 函数获得一些基尼系数,但是在寻找 ineq 包中的 Gini() 使用的公式时,我没有找到任何可靠的来源来了解它采用的公式。

有人知道吗?我读到过它使用了布朗公式,但我也发现它使用了洛伦兹曲线(45° 的曲线和“真实”分布)之间的差异。在ineq 页面中,它只说“Gini() 是基尼系数”。

我不确定在我的论文中应该写哪个公式,欢迎任何帮助。:)

谢谢!

  • 2 个回答
  • 47 Views
上一页
下一页

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve