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
Stephen
Asked: 2025-04-28 23:29:02 +0800 CST

C++ 中基于范围的 for 循环在 std::optional<Container> 上不起作用

  • 10

让我先从一段C++代码开始,它简化了我在实际代码库中遇到的问题。我用--std=c++20和编译了它--std=c++17。下面的第一个 for 循环没有问题;而第二个 for 循环(它返回结果)std::optional<Container>在我尝试过的所有多个容器中都不行。我想了解原因:

#include <iostream>
#include <optional>
#include <string>
#include <unordered_set>

std::unordered_set<std::string> GenerateSet() {                                                                                                                                                                                                      
  std::unordered_set<std::string> names = {"a", "b"};                                                                                                                                                                                                
  return names;                                                                                                                                                                                                                                      
}

std::optional<std::unordered_set<std::string>> GenerateOptionalSet() {                                                                                                                                                                               
  std::unordered_set<std::string> names = {"a", "b"};                                                                                                                                                                                                
  return names;                                                                                                                                                                                                                                      
}

int main() {                                                                                                                                                                                                                                         
  std::cout << "When a set is returned: {";                                                                                                                                                                                                          
  for (const auto& e : GenerateSet()) {                                                                                                                                                                                                              
    std::cout << e << " ";                                                                                                                                                                                                                           
  }                                                                                                                                                                                                                                                  
  std::cout << "}" << std::endl;                                                                                                                                                                                                                     
                                                                                                                                                                                                                                                     
  std::cout << "When a optional of a set is returned: {";                                                                                                                                                                                            
  for (const auto& e : GenerateOptionalSet().value()) {                                                                                                                                                                                              
    std::cout << e << " ";                                                                                                                                                                                                                           
  }                                                                                                                                                                                                                                                  
  std::cout << "}" << std::endl;                                                                                                                                                                                                                     
                                                                                                                                                                                                                                                     
  return 0;                                                                                                                                                                                                                                          
}

结果是运行时出现分段错误(相当新clang),或者在第二个 for 循环中根本没有迭代(gcc在古老的 Linux 机器上相当旧)。

std::optional<T>::value()这是我提到的有关: std::optional::value()的 URL,来自 cppreference.com

似乎有 4 个不同的版本。我不太确定这 4 个重写函数中哪个版本会被调用,以及为什么它没有按我预期的方式工作(即只是循环遍历返回的临时值std::optional<T>)。

c++
  • 1 个回答
  • 127 Views
Martin Hope
Kaligule
Asked: 2025-04-28 23:25:33 +0800 CST

检测群体中的碰撞

  • 6

设置:带有群和鸟类的小行星克隆

我想用游戏引擎 Bevy 和物理引擎 Avian 在 Rust 中制作一个小行星克隆。我已经有了子弹和小行星的组件。它们生成时也会获得一个碰撞器。

use bevy::prelude::*;
use avian2d::prelude::*;

#[derive(Component)]
struct Bullet;

#[derive(Component)]
struct Asteroid

fn setup(

) {
    asteroid_handle =  asset_server.load("asteroid.png");
    bullet_handle = asset_server.load("bullet.png");
    commands.spawn(
        (
            Asteroid,
            Sprite::from_image(asteroid_handle),
            Collider::circle(50.),
        )
    );
    commands.spawn(
        (
            Bullet,
            Sprite::from_image(bullet_handle),
            Collider::circle(5.),
        )
    );
}

(当然有一些代码,所以它们可以移动、转动等,但这与问题无关)

问题:寻找子弹和小行星之间的碰撞

实体之间的相互作用是我遇到困难的地方:我想检测小行星何时被子弹击中(这样我就可以让子弹消失并摧毁小行星,但我还不知道如何做)检测碰撞实际上非常容易,我只需监听碰撞事件即可。

fn print_collisions(mut collision_event_reader: EventReader<Collision>) {
    for Collision(contacts) in collision_event_reader.read() {
        println!(
            "Entities {} and {} are colliding",
            contacts.entity1,
            contacts.entity2,
        );
    }
}

这确实按预期打印出了碰撞。但它包含了飞船与子弹、飞船与小行星之间的碰撞……这里我只得到了两个实体,没有更多信息。我该如何测试它们是否包含我想要的组件?

我想要的只是子弹和小行星之间的碰撞。

人工智能的建议

我询问了人工智能,它给出了如下建议:

fn print_collisions(
    mut collision_event_reader: EventReader<Collision>,
    query: Query<(Entity, Option<&Bullet>, Option<&Asteroid>)>,
) {
    for Collision(contacts) in collision_event_reader.read() {
        let (entity1, bullet1, asteroid1) = query.get(contacts.entity1).unwrap_or((contacts.entity1, None, None));
        let (entity2, bullet2, asteroid2) = query.get(contacts.entity2).unwrap_or((contacts.entity2, None, None));

        // Check if one entity is a Bullet and the other is an Asteroid
        if (bullet1.is_some() && asteroid2.is_some()) || (bullet2.is_some() && asteroid1.is_some()) {
            println!(
                "Bullet {} collided with Asteroid {}",
                if bullet1.is_some() { entity1 } else { entity2 },
                if asteroid1.is_some() { entity1 } else { entity2 },
            );
        }
    }
}

我想这应该可行,但在我看来效率很低。我们已经有了事件中的实体,应该没必要再查询所有子弹和小行星来确认它们是否在查询范围内。

我正在寻找:一个简单的解决方案

我是 Rust 和 Bevy 的初学者。我有一些编程经验(主要是 Python)以及其他游戏引擎(例如 Godot),而且到目前为止,我编写的所有 Bevy 代码看起来都很优雅且模块化。这真的让我印象深刻。所以我正在寻找一个简单而优雅的解决方案。

rust
  • 1 个回答
  • 62 Views
Martin Hope
User
Asked: 2025-04-28 23:18:20 +0800 CST

如何修复动画混合?

  • 5

我有一段代码,点击屏幕左侧或右侧时,可以前后滚动全屏图像。当图像出现在屏幕上时,它会执行以下动画类型之一:上、下、左、右、放大、缩小——每个动画都包含两个子动画(第一个动画是快速动画,第二个动画是循环动画)。

问题是,切换图像时,动画坐标有时会叠加。正常情况下,动画应该只影响 X、Y 或 Scale 中的一个。但就我的情况而言,图像有时会沿对角线(X + Y)移动,动画会超出图像边界,导致屏幕上出现黑色区域​​。这种情况不应该发生。我该如何解决这个问题?

我removeAllAnimations在每个动画之前都使用它,但没有帮助。

完整代码:

class ReaderController: UIViewController, CAAnimationDelegate {
    
    var pagesData = [PageData]()
    var index = Int()
    var pageIndex: Int = -1
    
    let pageContainer: UIView = {
        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    let pageViews: [PageLayout] = {
        let view = [PageLayout(), PageLayout()]
        view[0].translatesAutoresizingMaskIntoConstraints = false
        view[1].translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    private weak var currentTransitionView: PageLayout?
        
    override func viewDidLoad() {
        super.viewDidLoad()

        setupViews()
        setupConstraints()

        pageViews[0].index = index
        pageViews[1].index = index
        pageViews[0].pageIndex = pageIndex
        pageViews[1].pageIndex = pageIndex
        
        pageTransition(animated: false, direction: "fromRight")
    }
        
    func setupViews() {
        pageContainer.addSubview(pageViews[0])
        pageContainer.addSubview(pageViews[1])
        view.addSubview(pageContainer)
    }
        
    func setupConstraints() {
        pageContainer.topAnchor.constraint(equalTo: view.topAnchor, constant: 0.0).isActive = true
        pageContainer.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0.0).isActive = true
        pageContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0.0).isActive = true
        pageContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0.0).isActive = true

        pageViews[0].topAnchor.constraint(equalTo: pageContainer.topAnchor).isActive = true
        pageViews[0].bottomAnchor.constraint(equalTo: pageContainer.bottomAnchor).isActive = true
        pageViews[0].leadingAnchor.constraint(equalTo: pageContainer.leadingAnchor).isActive = true
        pageViews[0].trailingAnchor.constraint(equalTo: pageContainer.trailingAnchor).isActive = true

        pageViews[1].topAnchor.constraint(equalTo: pageContainer.topAnchor).isActive = true
        pageViews[1].bottomAnchor.constraint(equalTo: pageContainer.bottomAnchor).isActive = true
        pageViews[1].leadingAnchor.constraint(equalTo: pageContainer.leadingAnchor).isActive = true
        pageViews[1].trailingAnchor.constraint(equalTo: pageContainer.trailingAnchor).isActive = true
    }
        
    func loadData(fileName: Any) -> PagesData {
        var url = NSURL()
        url = Bundle.main.url(forResource: "text", withExtension: "json")! as NSURL
        let data = try! Data(contentsOf: url as URL)
        let person = try! JSONDecoder().decode(PagesData.self, from: data)
        return person
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let location = touch.location(in: view.self)

            if view.safeAreaInsets.left > 30 {
                if (location.x > self.view.frame.size.width - (view.safeAreaInsets.left * 1.5)) {
                    pageTransition(animated: true, direction: "fromRight")
                } else if (location.x < (view.safeAreaInsets.left * 1.5)) {
                    pageTransition(animated: true, direction: "fromLeft")
                }
            }

            else {
                if (location.x > self.view.frame.size.width - 40) {
                    pageTransition(animated: true, direction: "fromRight")
                } else if (location.x < 40) {
                    pageTransition(animated: true, direction: "fromLeft")
                }
            }
        }
        
    }
    
    func pageTransition(animated: Bool, direction: String) {
        let result = loadData(fileName: pagesData)
        
        switch direction {
        case "fromRight":
            pageIndex += 1
        case "fromLeft":
            pageIndex -= 1
        default: break
        }
        
        pageViews[0].pageIndex = pageIndex
        pageViews[1].pageIndex = pageIndex
        
        guard pageIndex >= 0 && pageIndex < result.pagesData.count else {
            pageIndex = max(0, min(pageIndex, result.pagesData.count - 1))
            return
        }
        
        let fromView = pageViews[0].isHidden ? pageViews[1] : pageViews[0]
        let toView = pageViews[0].isHidden ? pageViews[0] : pageViews[1]
        toView.imageView.layer.removeAllAnimations()
        toView.imageView.transform = .identity
        toView.configure(theData: result.pagesData[pageIndex])
        if animated {
            fromView.isHidden = true
            toView.isHidden = false
        } else {
            fromView.isHidden = true
            toView.isHidden = false
        }
    }
    
}

class PageLayout: UIView {
            
    var index = Int()
    var pageIndex = Int()
    
    let imageView: UIImageView = {
        let image = UIImageView()
        image.contentMode = .scaleAspectFill
        image.translatesAutoresizingMaskIntoConstraints = false
        return image
    }()

    var imageViewTopConstraint = NSLayoutConstraint()
    var imageViewBottomConstraint = NSLayoutConstraint()
    var imageViewLeadingConstraint = NSLayoutConstraint()
    var imageViewTrailingConstraint = NSLayoutConstraint()
    
    var imagePosition = ""
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(imageView)
        setupConstraints()
    }
    
    func setupConstraints() {
        
        imageView.layer.removeAllAnimations()
        imageView.transform = .identity
        
        removeConstraints([imageViewTopConstraint, imageViewBottomConstraint, imageViewLeadingConstraint,
                           imageViewTrailingConstraint])
        
        switch imagePosition {
            
        case "top":
            
            imageView.transform = .identity
            
            imageViewTopConstraint = imageView.topAnchor.constraint(equalTo: topAnchor, constant: -40.0)
            imageViewBottomConstraint = imageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0.0)
            imageViewLeadingConstraint = imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0.0)
            imageViewTrailingConstraint = imageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0.0)
            
            addConstraints([imageViewTopConstraint, imageViewBottomConstraint, imageViewLeadingConstraint, imageViewTrailingConstraint])
            
            UIView.animate(withDuration: 2.0, delay: 0, options: [.curveEaseOut, .allowUserInteraction, .beginFromCurrentState], animations: {
                self.imageView.transform = CGAffineTransform(translationX: 0, y: 40.0)
            }, completion: { _ in
                UIView.animate(withDuration: 6.0, delay: 0, options: [.curveLinear, .autoreverse, .repeat, .beginFromCurrentState, .allowUserInteraction], animations: {
                    self.imageView.transform = self.imageView.transform.translatedBy(x: 0, y: -40.0)
                }, completion: nil)
            })
            
        case "bottom":
            
            imageView.transform = .identity
            
            imageViewTopConstraint = imageView.topAnchor.constraint(equalTo: topAnchor, constant: 0.0)
            imageViewBottomConstraint = imageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 40.0)
            imageViewLeadingConstraint = imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0.0)
            imageViewTrailingConstraint = imageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0.0)
            
            addConstraints([imageViewTopConstraint, imageViewBottomConstraint, imageViewLeadingConstraint, imageViewTrailingConstraint])
            
            UIView.animate(withDuration: 2.0, delay: 0, options: [.curveEaseOut, .allowUserInteraction, .beginFromCurrentState], animations: {
                self.imageView.transform = CGAffineTransform(translationX: 0, y: -40)
            }, completion: { _ in
                UIView.animate(withDuration: 6.0, delay: 0, options: [.curveLinear, .autoreverse, .repeat, .beginFromCurrentState, .allowUserInteraction], animations: {
                    self.imageView.transform = self.imageView.transform.translatedBy(x: 0, y: 40)
                }, completion: nil)
            })
            
        case "left":
            
            imageView.transform = .identity
            
            imageViewTopConstraint = imageView.topAnchor.constraint(equalTo: topAnchor, constant: 0.0)
            imageViewBottomConstraint = imageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0.0)
            imageViewLeadingConstraint = imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: -40.0)
            imageViewTrailingConstraint = imageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0.0)
            
            addConstraints([imageViewTopConstraint, imageViewBottomConstraint, imageViewLeadingConstraint, imageViewTrailingConstraint])
            
            UIView.animate(withDuration: 2.0, delay: 0, options: [.curveEaseOut, .allowUserInteraction, .beginFromCurrentState], animations: {
                self.imageView.transform = CGAffineTransform(translationX: 40, y: 0)
            }, completion: { _ in
                UIView.animate(withDuration: 6.0, delay: 0, options: [.curveLinear, .autoreverse, .repeat, .beginFromCurrentState, .allowUserInteraction], animations: {
                    self.imageView.transform = self.imageView.transform.translatedBy(x: -40, y: 0)
                }, completion: nil)
            })
            
        case "right":
            
            imageView.transform = .identity
            
            imageViewTopConstraint = imageView.topAnchor.constraint(equalTo: topAnchor, constant: 0.0)
            imageViewBottomConstraint = imageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0.0)
            imageViewLeadingConstraint = imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0.0)
            imageViewTrailingConstraint = imageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 40.0)
            
            addConstraints([imageViewTopConstraint, imageViewBottomConstraint, imageViewLeadingConstraint, imageViewTrailingConstraint])
            
            UIView.animate(withDuration: 2.0, delay: 0, options: [.curveEaseOut, .allowUserInteraction, .beginFromCurrentState], animations: {
                self.imageView.transform = CGAffineTransform(translationX: -40, y: 0)
            }, completion: { _ in
                UIView.animate(withDuration: 6.0, delay: 0, options: [.curveLinear, .autoreverse, .repeat, .beginFromCurrentState, .allowUserInteraction], animations: {
                    self.imageView.transform = self.imageView.transform.translatedBy(x: 40, y: 0)
                }, completion: nil)
            })
            
        case "zoomin":
            
            imageView.transform = CGAffineTransformScale(.identity, 1.0, 1.0)
            
            imageViewTopConstraint = imageView.topAnchor.constraint(equalTo: topAnchor, constant: 0.0)
            imageViewBottomConstraint = imageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0.0)
            imageViewLeadingConstraint = imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0.0)
            imageViewTrailingConstraint = imageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0.0)
            
            addConstraints([imageViewTopConstraint, imageViewBottomConstraint, imageViewLeadingConstraint, imageViewTrailingConstraint])
            
            UIView.animate(withDuration: 2.0, delay: 0, options: [.curveEaseOut, .allowUserInteraction, .beginFromCurrentState], animations: {
                self.imageView.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
            }, completion: { _ in
                UIView.animate(withDuration: 6.0, delay: 0, options: [.curveLinear, .autoreverse, .repeat, .beginFromCurrentState, .allowUserInteraction], animations: {
                    self.imageView.transform = .identity
                }, completion: nil)
            })
            
        case "zoomout":
            
            imageView.transform = CGAffineTransformScale(.identity, 1.1, 1.1)
            
            imageViewTopConstraint = imageView.topAnchor.constraint(equalTo: topAnchor, constant: 0.0)
            imageViewBottomConstraint = imageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0.0)
            imageViewLeadingConstraint = imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0.0)
            imageViewTrailingConstraint = imageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0.0)
            
            addConstraints([imageViewTopConstraint, imageViewBottomConstraint, imageViewLeadingConstraint, imageViewTrailingConstraint])
            
            UIView.animate(withDuration: 2.0, delay: 0, options: [.curveEaseOut, .allowUserInteraction, .beginFromCurrentState], animations: {
                self.imageView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
            }, completion: { _ in
                UIView.animate(withDuration: 6.0, delay: 0, options: [.curveLinear, .autoreverse, .repeat, .beginFromCurrentState, .allowUserInteraction], animations: {
                    self.imageView.transform = self.imageView.transform.scaledBy(x: 1.1, y: 1.1)
                }, completion: nil)
            })
            
        default:
            
            imageView.transform = .identity
            
            imageViewTopConstraint = imageView.topAnchor.constraint(equalTo: topAnchor, constant: 0.0)
            imageViewBottomConstraint = imageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: 0.0)
            imageViewLeadingConstraint = imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 0.0)
            imageViewTrailingConstraint = imageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: 0.0)
            
            addConstraints([imageViewTopConstraint, imageViewBottomConstraint, imageViewLeadingConstraint, imageViewTrailingConstraint])
        }
    }
        
    func configure(theData: PageData) {
        imageView.image = UIImage(named: "page\(pageIndex+1)")
        imagePosition = theData.imagePosition
        setupConstraints()
    }
    
    required init?(coder: NSCoder) {
        fatalError("Not happening")
    }
    
}

struct PagesData: Decodable {
    var pagesData: [PageData]
}

struct PageData: Decodable {
    let textData, textPosition, textColor, shadowColor, textAlignment, imagePosition: String
}

JSON:

{
    "pagesData" : [
        
        {
            "textData" : "",
            "textPosition" : "topLeft",
            "textColor" : "FFFFFF",
            "shadowColor" : "000000",
            "textAlignment" : "left",
            "imagePosition" : "left",
        },
        
        {
            "textData" : "",
            "textPosition" : "bottomLeft",
            "textColor" : "FFFFFF",
            "shadowColor" : "000000",
            "textAlignment" : "left",
            "imagePosition" : "bottom",
        },
        
        {
            "textData" : "",
            "textPosition" : "zoomin",
            "textColor" : "FFFFFF",
            "shadowColor" : "000000",
            "textAlignment" : "left",
            "imagePosition" : "right",
        },
        
        {
            "textData" : "",
            "textPosition" : "bottomCenter",
            "textColor" : "FFFFFF",
            "shadowColor" : "000000",
            "textAlignment" : "left",
            "imagePosition" : "zoomout",
        },
        
        {
            "textData" : "",
            "textPosition" : "topLeft",
            "textColor" : "FFFFFF",
            "shadowColor" : "000000",
            "textAlignment" : "left",
            "imagePosition" : "left",
        },
        
    ]
}
  • 1 个回答
  • 37 Views
Martin Hope
ValExi
Asked: 2025-04-28 23:12:08 +0800 CST

析构函数和继承中的“运算符~”

  • 7

从上一个问题中我知道,在~base()调用派生类时,它首先构造一个临时基对象,然后operator~()在临时对象上调用临时基,最后销毁临时对象。

但是当基类没有时operator~,在派生类中调用base::~base()仍然可以调用基类的析构函数。

为什么当基类有时会发生错误operator~?

#include <iostream>
using namespace std;
class base
{
public:
    base(){cout << "constructor base \n";}
    ~base(){cout << "destructor base \n";}
    void operator~(){cout << "operator ~ \n";}
};

class derived : public base
{
public:
    derived(){cout << "constructor derived \n";}
    ~derived(){base::~base();cout << "destructor derived \n";}
};

编译器版本信息:

g++.exe (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

错误:

cmd /c chcp 65001>nul && C:\mingw64\bin\g++.exe -fdiagnostics-color=always -g "D:\Valkyrie-text\simple text\text.cpp" -o "D:\Valkyrie-text\simple text\text.exe"
D:\Valkyrie-text\simple text\text.cpp: In destructor 'derived::~derived()':
D:\Valkyrie-text\simple text\text.cpp:15:28: error: no matching function for call to 'derived::~derived()'
     ~derived(){base::~base();cout << "destructor derived \n";}
                            ^
D:\Valkyrie-text\simple text\text.cpp:7:5: note: candidate: 'base::~base()'
     ~base(){cout << "destructor base \n";}
     ^
D:\Valkyrie-text\simple text\text.cpp:7:5: note:   candidate expects 1 argument, 0 provided
c++
  • 1 个回答
  • 147 Views
Martin Hope
Raj
Asked: 2025-04-28 23:11:34 +0800 CST

如何输出与查询匹配的文档数量?

  • 5

我想输出与特定查询匹配的文档数量,该查询是一个布尔值,因此显示值为“true”的文档数量。我在 Stack Overflow 上找到了几个与此相关的问题,但只有下面的代码接近我的需求。

以下代码在控制台中打印出正确的数字,但我需要帮助将其输出到屏幕上。

final Future<void> activityDone = FirebaseFirestore
      .instance
      .collection('user')
      .doc(FirebaseAuth.instance.currentUser!.uid)
      .collection('list')
      .doc(widget.docId).collection('activity').where("status", isEqualTo: true)
      .count().get().then(
        (res) => print(res.count),
    onError: (e) => print("Error completing: $e"),
  );

我无法让这个计数代码起作用。

String count = activityDone.toString();

我想在这样的文本中使用计数代码

Text("Activities done = $count"),

完整代码

child: StreamBuilder(
  stream: FirebaseFirestore.instance
          .collection('user')
        .doc(FirebaseAuth.instance.currentUser!.uid)
          .collection('list')
          .doc(widget.docId).collection('activity').orderBy('xTimeStamp', descending: false)
        .snapshots(),
  ),
  builder: (context, snapshot) {

    final xSnapshot = snapshot.data?.docs;

    final Future<void> activityDone = FirebaseFirestore
      .instance
      .collection('user')
      .doc(FirebaseAuth.instance.currentUser!.uid)
      .collection('list')
      .doc(widget.docId).collection('activity')
      .where("status", isEqualTo: true)
      .count()
      .get().then(
        (res) => print(res.count),
        onError: (e) => print("Error completing: $e"),
    );

    String count = activityDone.toString();

    if (xSnapshot == null) {
      // Error
    }, else {
      Text("Activities done = $count"),
    }    
}

错误 在此处输入图片描述 在此处输入图片描述

  • 1 个回答
  • 92 Views
Martin Hope
BATMAN_2008
Asked: 2025-04-28 22:56:07 +0800 CST

Quarkus WebSockets Next 使用 @WebSocket 注释时拦截 HTTP GET 请求

  • 5

从 移动quarkus-websocket到之后quarkus-websockets-next,任何对路径的 HTTP GET@WebSocket现在都会出现错误

"Connection" header must be "Upgrade"

这是因为新的扩展会拦截每个匹配的请求并将其视为 WebSocket 握手。

在旧quarkus-websocket模型中,@ServerEndpoint仅处理真正的 WebSocket 升级;对同一 URL 的普通 GET 将会传递到 JAX-RS 资源。

使用quarkus-websockets-next,@WebSocket(path="/…")会为该路径上的所有 HTTP 方法安装一个 Vert.x 处理程序。缺少必需的 Connection: Upgrade 标头的标准 GET 请求会被捕获并拒绝,导致任何 REST 逻辑无法运行。

下面是一个最小的 Quarkus 项目,显示:

  1. 遗产(quarkus-websockets):

    • REST@GET /chat端点
    • JSR-356 WebSocket @ServerEndpoint("/chat")
      → GET有效(200 OK),WS有效
  2. 下一个(quarkus-websockets-next):

    • 相同的 REST 资源
    • 新建@WebSocket(path = "/chat")
      → Any GET /chat现在失败
"Connection" header must be "Upgrade"

样本复现使用:

<dependency>
  <groupId>io.quarkus</groupId>
  <artifactId>quarkus-websockets</artifactId>
</dependency>

ChatResource.java:

@Path("/chat")
@ApplicationScoped
public class ChatResource {
    @GET
    public String hello() {
        return "Hello from REST!";
    }
}

ChatEndpoint.java:

@ServerEndpoint("/chat")
@ApplicationScoped
public class ChatEndpoint {
    @OnOpen
    public void onOpen(Session session) { /*...*/ }

    @OnMessage
    public void onMessage(Session session, String msg) {
        session.getAsyncRemote().sendText("Echo:" + msg);
    }
}

行为

GET http://localhost:8080/chat → 200 OK,返回“Hello from REST!​​”

ws://localhost:8080/chat → WebSocket 握手成功

随着新的quarkus-websockets-next:

<dependency>
  <groupId>io.quarkus</groupId>
  <artifactId>quarkus-websockets-next</artifactId>
</dependency>

ChatResource.java (unchanged):

@Path("/chat")
@ApplicationScoped
public class ChatResource {
    @GET
    public String hello() {
        return "Hello from REST!";
    }
}

ChatSocket.java:

@WebSocket(path = "/chat")
@ApplicationScoped
public class ChatSocket {
    @OnOpen
    public void onOpen(WebSocketConnection conn) { /*...*/ }

    @OnMessage
    public void onMessage(WebSocketConnection conn, String msg) {
        conn.sendText("Echo:" + msg).subscribe().with(r -> {}, t -> {});
    }
}

行为

GET http://localhost:8080/chat → 失败

"Connection" header must be "Upgrade"

ws://localhost:8080/chat → WebSocket 握手成功

这是预期结果quarkus-websockets-next还是一个 bug?因为我正在为标准规范实现一些端点,这些端点可能类似于:

/queries/{queryName}/events

根据规范,它应该执行以下操作:

Returns all events that match the query or creates a new Websocket subscription.

之前这个功能正常,quarkus-websockets但现在 GET 请求失败了,这quarkus-websockets-next有点令人困惑,这是否是一个需要修复的问题。

java
  • 1 个回答
  • 39 Views
Martin Hope
Isaac Blanc
Asked: 2025-04-28 22:23:28 +0800 CST

FiPy 中的热方程单位

  • 6

问题

当使用 FiPy 模拟热扩散方程时,使用体积特性是否正确?

语境

我正在用显式源项求解瞬态热扩散方程。

热扩散偏微分方程

在哪里:

  • T 是温度[K]
  • C 是体积热容量 [J/m³ K]
  • k 是电导率 [W/m·K]
  • S 是体积热源 [W/m³]

我在 FiPy 中将其表示如下:

eq = TransientTerm(C) == DiffusionTerm(k) + source

研究

  • 首先,上述偏微分方程中的单位都一致。瞬态项的单位为 [J/m³ s],简化为 [W/m³]。扩散项中 k 与 T 的乘积单位为 [W/m],应用这两个纳布拉公式后,将其除以 [m] 两次。因此,扩散项的单位为 [W/m³]。源项的单位为 [W/m³]。
  • diffuse.mesh1D示例展示了如何在 FiPy 中求解此偏微分方程。它们使用 ρCp 作为过渡系数。我假设它们的 Cp 表示比热容(重量热容),因此 ρCp(即比热容与密度的乘积)是体积热容。
  • 大约一百万年前的这个帖子提到了使用体积源项会导致热扩散误差。一开始这让我很困惑,但我认为这是因为作者用热扩散率来写他们的偏微分方程,而不是分别使用瞬态系数和扩散系数。
modeling
  • 1 个回答
  • 24 Views
Martin Hope
user29295031
Asked: 2025-04-28 22:00:43 +0800 CST

将月份缩写转换为全名

  • 8

我有这个函数可以将英语月份转换为法语月份:

def changeMonth(month):
    global CurrentMonth
    match month:
        case "Jan":
            return "Janvier"
        case "Feb":
            return "Février"
        case "Mar":
            return "Mars"
        case "Apr":
            return "Avril"
        case "May":
            return "Mai"
        case "Jun":
            return "Juin"
        case "Jul":
            return "Juillet"
        case "Aug":
            return "Août"
        case "Sep":
            return "Septembre"
        case "Oct":
            return "Octobre"
        case "Nov":
            return "Novembre"
        case "Dec":
            return "Décembre"

        # If an exact match is not confirmed, this last case will be used if provided
        case _:
            return ""

我有一只熊猫df["month"]= df['ic_graph']['month'].tolist():

在此处输入图片描述

现在我要找的是通过 changeMonth 函数传递 df["month"] col 来显示法国月份的 df["month"]

顺便说一句,我不想​​使用

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'fr_FR')
python
  • 3 个回答
  • 90 Views
Martin Hope
Zebrafish
Asked: 2025-04-28 21:58:16 +0800 CST

为什么 Windows 只允许 GPU 使用一半的 RAM?

  • 5

以下是 Vulkan Capability 查看器在我的计算机上显示的内容:

MEMORY HEAP 0
    DEVICE SIZE 8321499136
    FLAGS
        DEVICE_LOCAL_BIT
        MULTI_INSTANCE_BIT

    MEMORY TYPE 0
        DEVICE_LOCAL_BIT
    MEMORY TYPE 1
        DEVICE_LOCAL_BIT

MEMORY HEAP 1
    DEVICE SIZE 16760438784
    FLAGS
    NONE

    MEMORY TYPE 0
        HOST_VISIBLE_BIT
        HOST_COHERENT_BIT
    MEMORY TYPE 0
        HOST_VISIBLE_BIT
        HOST_COHERENT_BIT

堆 0 是我的 GPU 设备,有 8GB 内存。堆 1 应该是我的 CPU 内存。我的 CPU 内存是 32GB,在 Windows 的任务管理器中也显示为 32GB,但在 Vulkan 的内存堆描述中,只有一半(16GB)显示。我查找了原因,并在 Microsoft 页面上的“计算图形内存”页面中找到了:

在 VidMm 向客户端报告准确的数据之前,它必须首先计算显存的总量。VidMm 使用以下内存类型和公式来计算显存数量:

系统总内存

This value is the total amount of system memory accessible to the operating system. Memory that the BIOS allocates doesn't appear in this number. For example, a computer with a 1 GB DIMM (1,024 MB) that has a BIOS that reserves 1 MB of memory appears to have 1,023 MB of system memory.

可供图形使用的总系统内存

This value is the total amount of system memory that is dedicated or shared to the GPU. This number is calculated as follows:
C++ 

图形可用系统内存总量 = MAX((系统内存总量 / 2), 64MB)

链接在这里。

我在想这是为什么。你的内存只有一半可以同时使用 Vulkan 和 DirectX,或者图形 API?这显然是 VidMm 报告的。我不知道 VidMm 是什么,但 DirectX 或 Vulkan 都会参考这个来查看有多少可用内存,结果它总是报告只有一半的内存?

就我而言,我有一个 8GB 的​​独立显卡,报告显示内存正确,但系统内存显示只有实际内存的一半,也就是 32GB 除以 2。如果是核显会怎么样?设备只能使用系统内存的一半?也就是说只能使用一半的设备内存?这种情况只在 Windows 上出现,现在也出现在其他操作系统上了?

windows
  • 1 个回答
  • 38 Views
Martin Hope
tripler25
Asked: 2025-04-28 21:04:35 +0800 CST

.NET Framework 4.8 上的 Azure Functions V1:未发现 TimerTrigger [未找到作业函数。请尝试将您的作业类和方法公开]

  • 5

我正在尝试在针对 .NET Framework 4.8 的 v1 Azure Functions 项目中运行计时器触发函数,但主机从未接收它:

  using System;
    using System.Threading.Tasks;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    
    namespace ScreeningSync
    {
        public static class ScreeningSyncFunction
        {
            [FunctionName("ScreeningSyncFunction")]
            public static async Task Run([TimerTrigger("*/5 * * * * *")] TimerInfo timer,ILogger log)
            {
                log.LogInformation($"Sync Triggered at {DateTime.UtcNow:O}");
    
                var config = new ConfigurationBuilder()
                    .SetBasePath(Environment.CurrentDirectory)
                    .AddJsonFile("local.settings.json", optional: true)
                    .AddEnvironmentVariables()
                    .Build();
    
                var services = new ServiceCollection()
                    .AddSingleton<IConfiguration>(config)
                    .Configure<OAuthSettings>(config.GetSection(nameof(OAuthSettings)))
                    .AddHttpClient()
                    .AddLogging(lb => lb.AddConsole())
                    .AddSingleton<ICrmHelper, CrmHelper>()
                    .AddSingleton<ICrmServiceClientService, CrmServiceClientService>()
                    .AddSingleton<IIntegrationLogService, CrmIntegrationLogService>()
                    .AddSingleton<IHttpClientWrapper, HttpClientWrapper>()
                    .AddSingleton<IScreeningRecordSyncService, ScreeningRecordSyncService>()
                    .BuildServiceProvider();
    
                var syncSvc = services.GetRequiredService<IScreeningRecordSyncService>();
                await syncSvc.GetAllScreeningRecords();
    
                log.LogInformation($"Sync Completed at {DateTime.UtcNow:O}");
            }
        }
    }

当我运行 func host start 时,我看到: 在此处输入图片描述

我的 csproj 目前包含以下内容:

    <Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net48</TargetFramework>
    <AzureFunctionsVersion>v1</AzureFunctionsVersion>
    <LangVersion>10.0</LangVersion>
    <OutputType>Library</OutputType>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Azure.WebJobs.Extensions" Version="2.3.0" />
    <PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Http" Version="1.2.0" />
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="1.0.39" />

    <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="3.1.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="3.1.0" />

    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.0" />
    <PackageReference Include="Microsoft.Extensions.Http" Version="3.1.0" />
    <PackageReference Include="Microsoft.Extensions.Logging" Version="3.1.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.1.0" />
  </ItemGroup>
</Project>

我尝试过:

  • 添加/删除 Microsoft.Azure.WebJobs.Extensions(v2.x、v3.x、v4.x)

  • 删除 Microsoft.Azure.WebJobs.Extensions.Http

  • 清除 bin/obj、dotnet nuget locals 全部 --clear、恢复、
    重建以及使用 --no-debug 和不同端口运行

每次我都会得到“0 个工作功能”或 Microsoft.Azure.WebJobs 之间的 NU1107 版本冲突(主机需要 2.3.x,扩展需要 3.x/4.x)。

我想知道的是:

在 v1/.NET-4.8 Functions 应用程序中我究竟需要哪些 NuGet 包(和版本)才能发现 [TimerTrigger]?

我在 host.json 中是否缺少任何额外的配置,或者在 v1 下注册计时器绑定所需的启动钩子?

提前感谢任何指导!

  • 1 个回答
  • 55 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