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
KOLYAN CAT4UP
Asked: 2025-04-26 23:19:09 +0800 CST

将类方法、类对象和泛型与 mypy 一起使用

  • 6

我使用以下代码创建 G 类的子类并将它们应该生成的模型类型传递给它们。

from typing import TypeVar, Type


class A:
    @classmethod
    def model_validate(cls):
        print('Done')


T = TypeVar('T', bound=A)


class G[T]:
    def __init__(self, model: Type[T]):
        self.model = model

    def func(self) -> None:
        print(self.model.model_validate())


G[A](A).func()

这工作正常,但 mypy 给出了这个错误:

error: "type[T]" has no attribute "model_validate"  [attr-defined]

我做错了什么?

python
  • 1 个回答
  • 31 Views
Martin Hope
Northernlad
Asked: 2025-04-26 22:48:11 +0800 CST

当我选择 WHERE column = '' 时,查询返回一个日期[重复]

  • 6
这个问题已经有答案了:
为什么在日期列中插入空字符串会产生 1900-01-01 (1 个回答)
21 小时前关闭。

我正在运行查询来检查是否有任何记录包含空白DateOfBirth,但返回的数据不是我所期望的。

我运行了以下命令:

SELECT TOP 5 DateOfBirth, *
FROM [MyDataBase].[dbo].[CustomerRecord] 
WHERE DateOfBirth = ''

当我运行这个程序时,我的结果显示如下行:

ID 出生日期 姓
1 1900-01-01 琼斯
2 1900-01-01 执事
6 1900-01-01 熏肉
10 1900-01-01 詹姆斯
12 1900-01-01 烧伤

显示Information_SCHEMA.Columns列定义为 date,COLUMN_DEFAULT为,NULL并IS_NULLABLE设置为YES。

那么为什么它不返回空白行呢?

sql
  • 2 个回答
  • 58 Views
Martin Hope
Rainbobow
Asked: 2025-04-26 22:25:58 +0800 CST

使用管道机制时,带有 stream=True 的 Python 请求无法正常工作。尝试获取远程视频时长

  • 4

我想知道远处视频文件(比如 mp4)的持续时间。

我已经知道如何获取本地视频文件的时长:

import xml.etree.ElementTree as eltt, subprocess as spr

def size_from_fn(file_name):
    size = eltt.fromstring(
        spr.run(["ffprobe",
            "-i", file_name,
            "-show_format", "-output_format", "xml"
            ], stdout = spr.PIPE, stderr = spr.STDOUT).stdout.decode()
        ).find("format").get("duration")
    return size

def size_from_fd(file_descriptor):
    size = eltt.fromstring(
        spr.run(["ffprobe",
            "-i", "pipe:0",
            "-show_format", "-output_format", "xml"
            ], stdin = file_descriptor, stdout = spr.PIPE, stderr = spr.STDOUT).stdout.decode()
        ).find("format").get("duration")
    return size

def size_from_data(file_name):
    size = eltt.fromstring(
        spr.run(["ffprobe",
            "-i", "pipe:0",
            "-show_format", "-output_format", "xml"
            ], input = data, stdout = spr.PIPE, stderr = spr.STDOUT).stdout.decode()
        ).find("format").get("duration")
    return size

一切运行正常

我还知道如何将 HTTP 请求作为文件描述符获取:

import requests as rq

def url_to_fd(url):
    req = rq.get(url, stream = True)
    return req.raw

它也有效

然而,两者的结合失败,并显示以下消息ffprobe:Invalid data found when processing input

我不知道为什么,我只知道从 URL 返回的文件描述符的区别在于不可搜索(单向读取),但是通过替换普通文件描述符的这种方法:

with open("test.mp4", "rb") as f:
    f.seek = None
    size_of_fd(f)

这是有效的,因此表明ffprobe不需要任何寻求

这样做也是可行的,所以我不知道发生了什么:

def get_duration(url):
    complete_data = url_to_fd(url).read()
    return size_of_data(complete_data)

我的问题是视频文件可能非常大,所以我无法下载整个视频。

测试视频网址

python
  • 1 个回答
  • 35 Views
Martin Hope
Bachi Shashikadze
Asked: 2025-04-26 21:19:51 +0800 CST

Quarto PowerPoint 幻灯片有两个并排的图表,幻灯片底部有描述性文字?

  • 6

如何创建一个四开本的 PowerPoint 演示文稿,其中并排显示两幅图,并在每张幻灯片的底部添加描述性文字(如屏幕截图所示)?我的问题是,文本出现在第二张幻灯片上,而不是同一张幻灯片上两幅图的底部。

---
title: "iris Presentation"
format: pptx
---
parts of the code are from: https://github.com/quarto-dev/quarto-cli/discussions/2403 
```{r, include=FALSE}
library(tidyverse)

# Create histogram for each species
spec_name <- unique(iris$Species)

make_hist <- function(spec) {
  iris |> 
    filter(Species == spec) |> 
    ggplot(aes(x = Petal.Length)) +
    geom_histogram(bins = 10, fill = "steelblue", color = "white") +
    labs(title = paste("Petal Length Histogram -", spec))
}

list_hist <- map(spec_name, make_hist)

# Create a second set of plots (random scatter plots)
make_random_plot <- function() {
  tibble(x = rnorm(50), y = rnorm(50)) |> 
    ggplot(aes(x, y)) +
    geom_point(color = "darkorange") +
    labs(title = "Random Scatter Plot")
}

list_random <- map(spec_name, ~ make_random_plot())

# Combine into a data frame
df <- tibble(spec = spec_name, 
             plot1 = list_hist, 
             plot2 = list_random)
```

```{r}
#| output: asis
res <- pmap_chr(df, \(spec, plot1, plot2) {
  knitr::knit_child(text = c(
    paste0("## ", spec, " - Summary"),
    
    "```{r}",
    "#| echo: false",
    "#| layout-ncol: 2",
    "plot1",
    "plot2",
    "```",
    
    "",
    
    paste("This slide shows the distribution of Petal Length for", spec,
          "alongside a comparison scatter plot of random values.")
  ), envir = environment(), quiet = TRUE)
})
cat(res, sep = '\n')
```

期望输出:

FD

  • 1 个回答
  • 56 Views
Martin Hope
Valentin Vignal
Asked: 2025-04-26 21:17:16 +0800 CST

如何使用 vitest 模拟 $env/static/public?

  • 5

我正在使用MY_VAR来自$env/static/public

import { MY_VAR } from '$env/static/public';

export const myVar = MY_VAR === 'true';

我想在一些测试中模拟它,以支持这两种场景:MY_VARbuild true/ false。但我做不到。我正在使用 vitest。

__mock__/env/static/public.ts我尝试使用以下命令设置模拟文件:

export const MY_VAR = 'false';

和vitest.config.ts:

export default defineConfig(({ mode }) => ({
    // ...
    resolve: {
        alias: {
            '$env/static/public': path.resolve(__dirname, '__mocks__/env/static/public')
        }
    }
}));

vi.mock我也尝试了、的一些组合vi.hoisted,vi.spyOn但无法使其发挥作用。

我怎样才能$env/static/public用 vitest 进行模拟?

svelte
  • 1 个回答
  • 21 Views
Martin Hope
hhk
Asked: 2025-04-26 21:00:04 +0800 CST

在使用 pytest 测试气流任务时,我收到一个错误

  • 6

在使用 pytest 测试气流时,我遇到了一个错误。

# tests/conftest.py

import datetime
import pytest
from airflow.models import DAG

@pytest.fixture
def test_dag():
    return DAG(
        "test_dag",
        default_args={
            "owner": "airflow",
            "start_date": datetime.datetime(2025, 4, 5),
            "end_date": datetime.datetime(2025, 4, 6)
        },
        schedule=datetime.timedelta(days=1)
    )

# tests/test_instance_context.py

import datetime

from airflow.models import BaseOperator
from airflow.models.dag import DAG
from airflow.utils import timezone

class SampleDAG(BaseOperator):
    template_fields = ("_start_date", "_end_date")

    def __init__(self, start_date, end_date, **kwargs):
        super().__init__(**kwargs)
        self._start_date = start_date
        self._end_date = end_date
    
    def execute(self, context):
        context["ti"].xcom_push(key="start_date", value=self.start_date)
        context["ti"].xcom_push(key="end_date", value=self.end_date)
        return context


def test_execute(test_dag: DAG):
    task = SampleDAG(
        task_id="test",
        start_date="{{ prev_ds }}",
        end_date="{{ ds }}",
        dag=test_dag
    )

    task.run(
        start_date=test_dag.default_args["start_date"], 
        end_date=test_dag.default_args["end_date"]
    )

    expected_start_date = datetime.datetime(2025, 4, 5, tzinfo=timezone.utc)
    expected_end_date = datetime.datetime(2025, 4, 6, tzinfo=timezone.utc)
    assert task.start_date == expected_start_date
    assert task.end_date == expected_end_date

测试代码已通过,但我在这里遇到了一个问题。

tests/test_instance_context.py [2025-04-26T12:51:18.289+0000] {taskinstance.py:2604} INFO - Dependencies not met for <TaskInstance: test_dag.test manual__2025-04-05T00:00:00+00:00 [failed]>, dependency 'Task Instance State' FAILED: Task is in the 'failed' state.
[2025-04-26T12:51:18.303+0000] {taskinstance.py:2604} INFO - Dependencies not met for <TaskInstance: test_dag.test manual__2025-04-06T00:00:00+00:00 [failed]>, dependency 'Task Instance State' FAILED: Task is in the 'failed' state.   
.

我想测试 task.run 来查看task.run和之间的区别task.execute。当我传递 jinja 变量时,airflow 会自动通过 run 方法渲染变量。

所以,我想看看 prev_ds、ds、start_date 和 end_date 是否成功渲染。但是我收到了上面的错误。

python
  • 1 个回答
  • 29 Views
Martin Hope
Shiela
Asked: 2025-04-26 20:28:13 +0800 CST

如何在组合框更改期间删除一个值

  • 6

我这里有一个列表框,可以与下面的代码一起正常工作。

列表框1

列表框

更新了整个代码:

Option Explicit
Dim bInit As Boolean ' ** module-scoped variable

Private Sub UserForm_Initialize()
    bInit = True  ' ** set UserForm_Initialize mode **from Taller
    clearAll
    Me.cmbName.Value = "Nory"
    Dim ws As Worksheet: Set ws = Worksheets("Sheet1")
    Dim i As Long
    Dim arr: arr = ws.Range("B1").CurrentRegion.Value
    Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")

    For i = 2 To UBound(arr)
        dict(arr(i, 2)) = arr(i, 1)
    Next
   ' ***
     If dict.exists(Me.cmbName.Value) Then
        Me.cmbTeam.Value = dict(Me.cmbName.Value)
        If Not cmbTeam.Value = "" And Not cmbDate.Value = "" And Not cmbName.Value = "" Then
            Team
            forListBoxUpdate 'calling forListBoxUpdate
            forDateCombobox 'filling in date dropdowns
            forNamesCombobox 'filling in names combobox as long as 3 comboboxes are not blank
        Else
            Team 'calling Team dropdowns in case team is blank or default cmbName value has no team
            cmbDate.Value = ""
            cmbName.Value = ""
        End If
    Else
            Team 'calling Team dropdowns in case team is blank or default cmbName value has no team
            cmbDate.Value = ""
            cmbName.Value = ""
    End If
    bInit = False  ' ** reset **from Taller
End Sub

Private Sub cmbDate_Change()
    If Not cmbTeam = "" And Not cmbName = "" Then
        forListBoxUpdate 'calling to show info if team and name not blank
        forNamesCombobox 'filling in cmbname dropdowns
    Else
        cmbDate.Clear 'if cmbteam and cmbname blank, cmdate should also be blank
    End If
End Sub

Private Sub cmbName_Change()
    forListBoxUpdate
End Sub

Private Sub cmbTeam_Change()
    cmbDate.Value = ""
    'cmbName.Value = "" 'issue, during initialize, default cmbname is removed.
    clearAll 'used this instead
    forDateCombobox 'fills in date dropdowns
End Sub



Sub forListBoxUpdate() 'to show info from sheets and to be called after the 3 comboboxes are filled
    Dim ws As Worksheet, colList As Collection
    Dim arrData, arrList, i As Long, j As Long
    
    Set colList = New Collection
    Set ws = Worksheets("Sheet2")
    arrData = ws.Range("A1:C" & ws.Cells(ws.Rows.count, "A").End(xlUp).Row)
    
        For i = 2 To UBound(arrData)
            If Format(arrData(i, 1), "mmmm yyyy") = Me.cmbDate.Value And arrData(i, 3) = Me.cmbName.Value Then
                colList.Add i, CStr(i)
            End If
    Next

    ReDim arrList(1 To colList.count + 1, 1 To UBound(arrData))
    For j = 1 To 3
        arrList(1, j) = arrData(1, j) ' header
        For i = 1 To colList.count
                arrList(i + 1, j) = arrData(colList(i), j)
        Next
    Next

    With Me.ListBox1
        .Clear
        .ColumnCount = UBound(arrData, 2)
        .list = arrList
    End With
    
    
    labelCount.Caption = ListBox1.ListCount - 1
End Sub

Sub clearAll() 'to clear comboboxes except teams
    If Not bInit Then cmbName.Value = ""  ' ** doesn't run when calling from UserForm_Initialize **from Taller
    cmbDate.Clear
    cmbName.Clear
    'cmbName.Value = ""
    ListBox1.Clear
End Sub

Sub Team() 'for adding the teams dropdown in cmbTeam
    clearAll
    Dim ws As Worksheet, _
        Dic As Object, _
        rCell As Range, _
        Key
    
    Set ws = Worksheets("Sheet1")
    Set Dic = CreateObject("Scripting.Dictionary")
    
    
    For Each rCell In ws.Range("A2", ws.Cells(Rows.count, "A").End(xlUp))
            If Not Dic.exists(rCell.Value) And Not rCell = "" Then
                Dic.Add rCell.Value, Nothing
            End If
    Next rCell
    
    For Each Key In Dic
        cmbTeam.AddItem Key
    Next
End Sub

Sub forNamesCombobox() 'for adding the names dropdown in cmbName
Dim ws As Worksheet, _
    Dic As Object, _
    rCell As Range, _
    Key

Set ws = Worksheets("Sheet1")
Set Dic = CreateObject("Scripting.Dictionary")


For Each rCell In ws.Range("B2", ws.Cells(Rows.count, "B").End(xlUp))
        If Not Dic.exists(rCell.Value) And rCell.Offset(0, -1) = cmbTeam.Value Then
            Dic.Add rCell.Value, Nothing
        End If
Next rCell

For Each Key In Dic
    cmbName.AddItem Key
Next
End Sub

Sub forDateCombobox() 'for adding the date dropdown in cmbDate
            Dim date1 As Variant
            Dim date2 As Variant
            date1 = Format(Now, "mmmm yyyy")
            date2 = Format(DateAdd("m", -1, CDate(date1)), "mmmm yyyy")
            
            With cmbDate
            .Clear
            .AddItem Format(date2, "mmmm yyyy")
            .AddItem Format(date1, "mmmm yyyy")
            .Value = Format(date1, "mmmm yyyy")
            End With
            
End Sub

工作表1

一个 B
团队 名字
鹦鹉 莉娜
乔治 诺里
乔治 最大限度
杰克 担

工作表2

一个 B 碳
日期 ID 名字
2025年3月25日 1101 莉娜
2025年4月25日 1102 莉娜
2025年3月25日 1103 诺里
2025年4月25日 1104 诺里
2025年3月25日 1105 担
2025年4月25日 1106 担

现在,在团队组合框的更改事件期间,我希望清除名称组合框(“Nory”或任何值cmbName都应被删除并消失)。

从上面的代码中,团队变更事件片段是:

Private Sub cmbTeam_Change()
    cmbDate.Value = ""
    'cmbName.Value = "" 'issue, during initialize, default cmbname is removed.
    clearAll 'used this instead
    forDateCombobox 'fills in date dropdowns
End Sub

Sub clearAll() 'to clear comboboxes except teams
    If Not bInit Then cmbName.Value = ""  ' ** doesn't run when calling from UserForm_Initialize **from Taller
    cmbDate.Clear
    cmbName.Clear
    'cmbName.Value = ""
    ListBox1.Clear
End Sub

即使我将在初始化期间插入cmbName.Value = ""到 sub 中clearAll,"Nory"也会被删除,但我不希望它在初始化时被删除。

如何修复上述代码,在初始化期间,“Nory”将保留,团队和日期也将保留,而当团队发生变化时,日期和姓名组合框将为空白。

非常感谢您的帮助。

excel
  • 1 个回答
  • 89 Views
Martin Hope
user30291405
Asked: 2025-04-26 20:13:36 +0800 CST

C# 在函数外部使用变量[重复]

  • 0
这个问题已经有答案了:
从另一个方法引用变量 (10 个答案)
昨天关闭。

如何在 function2 中使用 var?

private void function1()
{
    string var = "x";
}

private void function2()
{
    MessageBox.Show(var);
}

我无法将 var 的值传递给 function2,我搜索了论坛和互联网,但找不到解决方案。非常感谢大家。

c#
  • 1 个回答
  • 70 Views
Martin Hope
user3918219
Asked: 2025-04-26 19:03:52 +0800 CST

在 WordPress 中创建取货距离计算英里定价

  • 4

我成功地实现了上一个问题中的代码如何在 WordPress 中创建接送距离计算英里定价 我想做的是添加最低成本 40 来显示计算成本是否低于该成本,但真的很难获得 if 语句,有什么想法吗?

document.addEventListener('DOMContentLoaded', function() {
    let map;
    let directionsService;
    let directionsRenderer;

    function initMap() {
        // Initialize the Google Maps objects
        directionsService = new google.maps.DirectionsService();
        directionsRenderer = new google.maps.DirectionsRenderer();
        map = new google.maps.Map(document.getElementById('map'), {
            center: { lat: -34.397, lng: 150.644 },
            zoom: 8
        });
        directionsRenderer.setMap(map);
    }

    function calculateDistance() {
        const pickup = document.getElementById('pickup').value;
        const destination = document.getElementById('destination').value;

        if (pickup && destination) {
            const request = {
                origin: pickup,
                destination: destination,
                travelMode: 'DRIVING'
            };

            directionsService.route(request, function(result, status) {
                if (status == 'OK') {
                    directionsRenderer.setDirections(result);

                    const distance = result.routes[0].legs[0].distance.value / 1000; // distance in km
                    const cost = distance * 2; // Example: $2 per km

                    document.getElementById('distance').textContent = distance.toFixed(2) + ' km';
                    document.getElementById('total-cost').textContent = '$' + cost.toFixed(2);
                } else {
                    alert('Could not calculate distance: ' + status);
                }
            });
        } else {
            alert('Please enter both pickup and destination locations.');
        }
    }

    document.getElementById('calculate-button').addEventListener('click', calculateDistance);

    // Load the map
    initMap();
});

我尝试了 IF 和 Else 的各种测试,但没有成功

javascript
  • 1 个回答
  • 49 Views
Martin Hope
Emman
Asked: 2025-04-26 18:45:19 +0800 CST

如何创建一个现在列来表示某个值是否位于由其他列分组的先前行中?

  • 7

给定一个长格式表,其中包含两个“组”列,我想创建一个新列,该新列具有前一个TRUE组的集合中是否存在该值。

例子

请考虑下表,其中显示了两个人以及他们每天购买的东西。

df_groceries <- tibble::tribble(
   ~person,  ~day,          ~groceries,
    "gary", "Mon",          "tomatoes",
    "gary", "Mon",              "milk",
    "gary", "Mon",             "bread",
    "gary", "Mon",            "yogurt",
    "gary", "Tue",              "eggs",
    "gary", "Tue",            "cheese",
    "gary", "Tue",            "apples",
    "gary", "Wed",           "chicken",
    "gary", "Wed",              "rice",
    "gary", "Wed",            "apples",
    "gary", "Thu",           "lettuce",
    "gary", "Thu",             "sauce",
    "gary", "Fri",              "fish",
    "gary", "Fri",          "potatoes",
    "gary", "Fri",           "lettuce",
    "gary", "Sat",            "cereal",
    "gary", "Sat",           "bananas",
    "gary", "Sat",             "juice",
    "gary", "Sun",              "rice",
    "gary", "Sun",           "bananas",
    "gary", "Sun",            "cereal",
  "rachel", "Mon",           "spinach",
  "rachel", "Mon",         "mushrooms",
  "rachel", "Mon",             "pasta",
  "rachel", "Tue",         "mushrooms",
  "rachel", "Tue",          "broccoli",
  "rachel", "Tue",            "lemons",
  "rachel", "Tue",         "olive oil",
  "rachel", "Wed",          "avocados",
  "rachel", "Wed",            "lemons",
  "rachel", "Thu",    "chicken breast",
  "rachel", "Thu",            "quinoa",
  "rachel", "Thu",      "bell peppers",
  "rachel", "Fri",            "yogurt",
  "rachel", "Fri",           "berries",
  "rachel", "Fri",           "granola",
  "rachel", "Sat",            "yogurt",
  "rachel", "Sat",          "avocados",
  "rachel", "Sun",              "eggs",
  "rachel", "Sun",      "orange juice",
  "rachel", "Sun", "whole wheat bread"
  )

我想计算一个额外的列,以指示每件杂货是否是在前一天(特别是前一天,而不是任何前一天)购买的,并区分每个人。

例如,由于加里在星期二和星期三都得到了苹果,那么我们应该TRUE为加里标记星期三的苹果。

因此,所需的输出是:

df_groceries_desired_output <- 
  tibble::tribble(
   ~person,  ~day,          ~groceries, ~was_purchased_yesterday,
    "gary", "Mon",          "tomatoes",                      NA,
    "gary", "Mon",              "milk",                      NA,
    "gary", "Mon",             "bread",                      NA,
    "gary", "Mon",            "yogurt",                      NA,
    "gary", "Tue",              "eggs",                   FALSE,
    "gary", "Tue",            "cheese",                   FALSE,
    "gary", "Tue",            "apples",                   FALSE,
    "gary", "Wed",           "chicken",                   FALSE,
    "gary", "Wed",              "rice",                   FALSE,
    "gary", "Wed",            "apples",                    TRUE,
    "gary", "Thu",           "lettuce",                   FALSE,
    "gary", "Thu",             "sauce",                   FALSE,
    "gary", "Fri",              "fish",                   FALSE,
    "gary", "Fri",          "potatoes",                   FALSE,
    "gary", "Fri",           "lettuce",                    TRUE,
    "gary", "Sat",            "cereal",                   FALSE,
    "gary", "Sat",           "bananas",                   FALSE,
    "gary", "Sat",             "juice",                   FALSE,
    "gary", "Sun",              "rice",                   FALSE,
    "gary", "Sun",           "bananas",                    TRUE,
    "gary", "Sun",            "cereal",                    TRUE,
  "rachel", "Mon",           "spinach",                      NA,
  "rachel", "Mon",         "mushrooms",                      NA,
  "rachel", "Mon",             "pasta",                      NA,
  "rachel", "Tue",         "mushrooms",                    TRUE,
  "rachel", "Tue",          "broccoli",                   FALSE,
  "rachel", "Tue",            "lemons",                   FALSE,
  "rachel", "Tue",         "olive oil",                   FALSE,
  "rachel", "Wed",          "avocados",                   FALSE,
  "rachel", "Wed",            "lemons",                    TRUE,
  "rachel", "Thu",    "chicken breast",                   FALSE,
  "rachel", "Thu",            "quinoa",                   FALSE,
  "rachel", "Thu",      "bell peppers",                   FALSE,
  "rachel", "Fri",            "yogurt",                   FALSE,
  "rachel", "Fri",           "berries",                   FALSE,
  "rachel", "Fri",           "granola",                   FALSE,
  "rachel", "Sat",            "yogurt",                    TRUE,
  "rachel", "Sat",          "avocados",                   FALSE,
  "rachel", "Sun",              "eggs",                   FALSE,
  "rachel", "Sun",      "orange juice",                   FALSE,
  "rachel", "Sun", "whole wheat bread",                   FALSE
  )

我的尝试

我认为这应该像使用%in%运算符一样简单:

library(dplyr)

df_groceries |> 
  group_by(person) |> 
  mutate(day_as_number = case_match(day, 
                                    "Mon" ~ 1, 
                                    "Tue" ~ 2, 
                                    "Wed" ~ 3, 
                                    "Thu" ~ 4, 
                                    "Fri" ~ 5, 
                                    "Sat" ~ 6, 
                                    "Sun" ~ 7)) |> 
  mutate(was_purchased_yesterday = groceries %in% groceries[day_as_number == day_as_number - 1])

但我得到了毫无意义的结果:

df_groceries

## # A tibble: 41 × 5
## # Groups:   person [2]
##    person day   groceries day_as_number was_purchased_yesterday
##    <chr>  <chr> <chr>             <dbl> <lgl>                  
##  1 gary   Mon   tomatoes              1 FALSE                  
##  2 gary   Mon   milk                  1 TRUE                   
##  3 gary   Mon   bread                 1 TRUE                   
##  4 gary   Mon   yogurt                1 TRUE                   
##  5 gary   Tue   eggs                  2 FALSE                  
##  6 gary   Tue   cheese                2 TRUE                   
##  7 gary   Tue   apples                2 TRUE                   
##  8 gary   Wed   chicken               3 FALSE                  
##  9 gary   Wed   rice                  3 TRUE                   
## 10 gary   Wed   apples                3 TRUE                   
## # ℹ 31 more rows
## # ℹ Use `print(n = ...)` to see more rows
  • 1 个回答
  • 128 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