暖阳

文章 评论 浏览 31

暖阳 2025-02-20 23:12:31

我发现了这个问题:在没有应用于ESM文件的变压器周围似乎存在一些混乱。就我而言, jsdom-environment-global.spec.ts 从我的monorepo中的其他软件包导入了ESM模块。此导入触发了一个例外,因为玩笑试图通过 require()导入它,该被捕获,然后再次通过动态导入导入。然后,此动态导入引发了一个例外,即 ts 是未知的异常。我不确定为什么没有转换这些文件,但是从如何在开玩笑的自定义测试环境文件中使用Typescript?这似乎是正常的。

底线:不要从嘲笑中的ESM文件导入 testenvorlirnment 模块。

I found the issue: there seems to be some confusion around the transformer not being applied to ESM files. In my case, the jsdom-environment-global.spec.ts imported an ESM module from a different package within my monorepo. This import triggers an exception because jest tries to import it via require(), which is caught and then again imported via dynamic imports. This dynamic import then throws the exception that ts is an unknown exception. I'm not sure why these files haven't been transformed, but as of How to use TypeScript in a Custom Test Environment file in Jest? this seems to be normal.

Bottom line: don't import from ESM files within your jest testEnvironment module.

当尝试将TS文件用作自定义测试环境时,Jest为什么会抛出err_unknown_file_extension?

暖阳 2025-02-20 19:32:09

主要错误

tldr; PIP试图用TestPypi解决依赖性,但它们在另一个索引(PYPI)中。答案结束时解决方法。

我发布到 testpypi 的事实是发生这种情况的原因。我将解释为什么我所做的错误会出现,然后我将展示您将来如何解决这个问题。

pypi 和testpypi

pypi 之间的差异是Python包装指数。这是Python软件包的巨型索引,可以使用 pip install 安装。
TestPypi 是指定用于测试和发布的Python软件包索引,而无需触摸真实的软件包索引。在学习如何发布软件包时,它可能很有用。主要区别是它是一个完全独立的存储库。因此, testpypi 上的内容可能不是 pypi 上的内容。
我的研究有限,因此,如果我使任何人感到困惑,主要区别是它们是两个不同的软件包索引。一个是出于测试目的。

我将软件包发布到 testpypi 上,并将我的 pip install 设置为从该存储库安装。 不是 pypi ,而是 testpypi

为什么当我定义项目的依赖关系时,依赖性解决方案失败

,我根据PYPI的存在定义了它们。大多数依赖项都存在于PYPI中。 不是 testpypi。这意味着,当我从testpypi中要求我的软件包时,PIP只会查看testPypi,而PIP安装程序工作流则落入了这样的模式:

0.5。将获取存储库设置为testpypi和不是 pypi。

  1. 从testpypi
  2. 安装中拉软件包并检查依赖项
  3. 找到第一个依赖关系(例如BeautifulSoup4)
  4. 从testpypi中
  5. 成功安装BeautifulSoup44
    - 。这是因为BeautifureSoup4 实际上是在TestPypi中存在的。
  6. 转移到另一个依赖性(例如Rich)
  7. 无法从TestPypi中拉出
    - 。 TestPypi中不存在Rich。
  8. 找不到返回依赖。

为什么某些依赖性正如您在工作流程步骤 5中看到的奇怪作用。

beautifulsoup4 包装在TestPypi上找到。 (有人把它放在那里)。

但是,正如您在步骤 7中看到的。之所以发生此问题,是因为我将仓库设置为从testpypi安装,因为我的包裹的位置。这导致PIP使用testpypi。对于每个依赖性也是如此。

我如何解决。

我通过使用TestPypi来验证准确的构建伪像出版,然后跳到正常 pypi来测试安装和依赖安装。

解决方法

从testpypi

python3 -m pip install -i https://test.pypi.org/simple/simple/< package name>

install from pypi(默认情况>

python3 -m python3 -m pip install install <软件包名称>

testPypi的安装软件包,但pypi的依赖项

python docs docs很好地解释了这一点。

如果要允许PIP还从PYPI下载软件包,则可以指定-Extra-index-url指向PYPI。当您要测试的软件包具有依赖项时,这很有用:

python3 -m pip install-index-url https://test.pypi.org/simple/-extra-index-url https:// pypi .org/simple/your-ackage

Main Error

TLDR; Pip tries to resolve dependencies with TestPypi, but they are in another index (Pypi). Workarounds at end of answer.

The fact that I am publishing to TestPypi is the reason this has happened. I will explain why what I did made this error appear, and then I will show how you, from the future, may solve this.

Difference between Pypi and TestPypi

Pypi is the Python Package Index. It's a giant index of Python packages one may install from with pip install.
TestPypi is the Python Package Index designated for testing and publishing without touching the real Package Index. It can be useful in times when learning how to publish a package. The main difference is that it is a completely separate repository. Therefore, what's on TestPypi may not be exactly what's on Pypi.
My research was limited, so if I confused anyone, the main difference is that they are two different Package Indexes. One was made for testing purposes.

I published my package to TestPypi and set my pip install to install from that repository. Not Pypi, but TestPypi.

Why dependency resolution failed

When I defined my project's dependencies, I defined them based off of their Pypi presences. Most dependencies are present in Pypi. Not TestPypi. This meant that when I asked for my package from TestPypi, pip only looked at TestPypi, and the pip installer workflow fell out to a pattern like this:

0.5. Set fetching repository to TestPypi and Not Pypi.

  1. Pull package from TestPypi
  2. Install and examine dependencies
  3. Find first dependency (e.g. Beautifulsoup4)
  4. Pull dependency from TestPypi
  5. Successfully install Beautifulsoup4
    -. This is because beautifulsoup4 is actually present in the TestPypi.
  6. Move on to another dependency (e.g. rich)
  7. Fail to pull from TestPypi
    -. Rich is not present in TestPypi.
  8. Return dependency not found.

Why some dependencies oddly worked

As you see in workflow step 5., the beautifulsoup4 package was found on the TestPypi. (Someone had put it up there).
image to TestPypi page with beautifulsoup4
However, as you see in step 7., Rich is not found on the TestPypi index. This issue occurs because I set my repoistiroy to install from TestPypi because my that is where my package was held. This caused pip to use TestPypi. for every single dependency as well.

How I got around it.

I got around it by using TestPypi to verify accurate build artifact publishing, and then I jumped to Normal Pypi to test installation and dependency installation.

Workarounds

Install from TestPypi

python3 -m pip install -i https://test.pypi.org/simple/ <package name>

Install from Pypi (by default)

python3 -m pip install <package name>

Install package from TestPypi but dependencies from Pypi

The Python Docs explains this very well.

If you want to allow pip to also download packages from PyPI, you can specify --extra-index-url to point to PyPI. This is useful when the package you’re testing has dependencies:

python3 -m pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ your-package

Python PIP:PIP安装找不到满足要求的版本 - 尽管存在于pyproject.toml中

暖阳 2025-02-20 19:01:00

找不到模块:错误:无法解决'./app'

我遇到了同样的问题,经过长时间的研究,我意识到自己必须包括文件的后缀,我通过添加来解决我的问题 .tsx ./应用程序

实例:
具有错误的代码:<代码>从'./app'导入应用程序;

编译已修复:来自'./app.tsx'; 的导入应用程序

如果解决了您的问题,请尝试一下!

Module not found: Error: Can't resolve './App'

I had faced the same issue, after a long research, what I realized myself is that you've got to include suffix of your file, I fixed my issue by adding .tsx behind ./App

Instance:
Code having error: import App from './App';

Compilation Fixed: import App from './App.tsx';

Try it out if this fixes your issue!

ReactJS-找不到模块:错误:可以解决&#x27; app&#x27;

暖阳 2025-02-20 15:56:47

我认为您应该使用 Groupby,Nunique和NP.Where 来解决此问题。
请参阅以下有关此问题的讨论。
pandas-dataframe-check-check-check-frame-check-if-multiple-multiple-multiple-lows-有个性值

I think you should use groupby, nunique, and np.where to solve this issue.
See the following discussion regarding this problem.
pandas-dataframe-check-if-multiple-rows-have-the-same-value

如何与相同值合并DF的行

暖阳 2025-02-20 05:18:16

修复了问题,通过更新关闭内部的值来修复问题。

db.collection(collectionName)
            .whereField("payer", isEqualTo: Auth.auth().currentUser?.uid ?? "")
            .whereField("contributor", isEqualTo: contributorID)
            .addSnapshotListener { snapshot, error in
                
                self.toGetAmount = 0
                    
                    guard let doc = snapshot?.documents else {
                        print("No Doc Found")
                        return
                    }
                    
                DispatchQueue.main.async {
                    self.toGetbills = doc.compactMap { queryDocumentSnapshot -> Bill? in
                        let result = Result { try queryDocumentSnapshot.data(as: Bill.self) }
                        
                        switch result {
                        case .success(let bill):
                            self.toGetAmount += bill.itemPrice
                            return bill
                            
                        case .failure( _):
                            print("Failure To Get Bill Request")
                            return nil
                        }
                        
                    }
                }
            }

Fixed the issue by updating the value inside the closure.

db.collection(collectionName)
            .whereField("payer", isEqualTo: Auth.auth().currentUser?.uid ?? "")
            .whereField("contributor", isEqualTo: contributorID)
            .addSnapshotListener { snapshot, error in
                
                self.toGetAmount = 0
                    
                    guard let doc = snapshot?.documents else {
                        print("No Doc Found")
                        return
                    }
                    
                DispatchQueue.main.async {
                    self.toGetbills = doc.compactMap { queryDocumentSnapshot -> Bill? in
                        let result = Result { try queryDocumentSnapshot.data(as: Bill.self) }
                        
                        switch result {
                        case .success(let bill):
                            self.toGetAmount += bill.itemPrice
                            return bill
                            
                        case .failure( _):
                            print("Failure To Get Bill Request")
                            return nil
                        }
                        
                    }
                }
            }

stateObject不会更改出现,而是更改按钮点击的值

暖阳 2025-02-20 03:34:17

在您的代码中,您在使用 router.push 而不是 router.push()中使用的代码中。

inside your code you are using in the useEffect Router.push instead of router.push()

我的使用效果在预期时不会发射

暖阳 2025-02-19 22:31:40

如果您只希望循环继续进行直到到达工作表的末端,则可以使用:

function forloop() {

  let spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  let sheet = spreadsheet.getSheetByName("Sheet1");
  var rows = sheet.getDataRange().getValues().length;

  for (let i = 1; i < rows + 1; i++) {
    let currentCell = sheet.getRange(i, 1).getValue();
    let nextCell = sheet.getRange(i + 1, 1).getValue();

    if (currentCell + nextCell === 3) {
      sheet.getRange(i, 1).setBackground("#8e7cc3");
    }
  } // function ends
}

使用您给出的代码段,您才会在CurrentCell和NextCell的值最多总和3时突出显示该框的颜色。

但是,但是什么。我相信您正在尝试实现,这是每个第三行的强调,因此,如果您正在寻找的话,这也是解决方案:

function forloop() {

  let spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  let sheet = spreadsheet.getSheetByName("Sheet1");
  var rows = sheet.getDataRange().getValues().length;

  for (let i = 1; i < rows + 1; i++) {
    if (i%3 === 0) {
      sheet.getRange(i, 1).setBackground("#8e7cc3");
    }
  } // function ends
}

这是我第一次回答溢出问题的问题:),希望它会有所帮助。

If you simply want the loop to continue until it reaches the end of your sheet, you can use:

function forloop() {

  let spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  let sheet = spreadsheet.getSheetByName("Sheet1");
  var rows = sheet.getDataRange().getValues().length;

  for (let i = 1; i < rows + 1; i++) {
    let currentCell = sheet.getRange(i, 1).getValue();
    let nextCell = sheet.getRange(i + 1, 1).getValue();

    if (currentCell + nextCell === 3) {
      sheet.getRange(i, 1).setBackground("#8e7cc3");
    }
  } // function ends
}

With the code snippet you gave, you will highlight the box that color only when the values of currentCell and nextCell sum up to 3.

But what I believe you are trying to achieve is to highlight every third row, so here is the solution to that as well if it is what you are looking for:

function forloop() {

  let spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  let sheet = spreadsheet.getSheetByName("Sheet1");
  var rows = sheet.getDataRange().getValues().length;

  for (let i = 1; i < rows + 1; i++) {
    if (i%3 === 0) {
      sheet.getRange(i, 1).setBackground("#8e7cc3");
    }
  } // function ends
}

This is my first time answering a question on overflow :), hope it helps.

可以弄清楚如何完成我的循环(如何重置循环?)

暖阳 2025-02-19 19:57:50

JavaScript中的示例:可以对好的零件进行调整:

var doubled_words = /([A-Za-z\u00C0-\u1FFF\u2800-\uFFFD]+)\s+\1(?:\s|$)/gi;

\ b使用\ w用于单词边界,其中\ w等于[0-9A-Z_A-Z]。如果您不介意这种限制,那么接受的答案就可以了。

The example in Javascript: The Good Parts can be adapted to do this:

var doubled_words = /([A-Za-z\u00C0-\u1FFF\u2800-\uFFFD]+)\s+\1(?:\s|$)/gi;

\b uses \w for word boundaries, where \w is equivalent to [0-9A-Z_a-z]. If you don't mind that limitation, the accepted answer is fine.

重复单词的正则表达式

暖阳 2025-02-19 19:25:53

实际上,这与默认值无关,除非当您编写具有可变默认值的功能时,它通常是出乎意料的行为。

>>> def foo(a):
    a.append(5)
    print a

>>> a  = [5]
>>> foo(a)
[5, 5]
>>> foo(a)
[5, 5, 5]
>>> foo(a)
[5, 5, 5, 5]
>>> foo(a)
[5, 5, 5, 5, 5]

此代码中没有默认值,但是您会遇到完全相同的问题。

问题在于 foo 修改 当呼叫者不期望这是一个可突变的变量。如果称为 append_5 之类的函数,则这样的代码就可以了。然后,呼叫者将调用该功能以修改其传递的值,并可以预期行为。但是,这样的函数不太可能采用默认参数,并且可能不会返回列表(因为呼叫者已经对该列表有一个引用;它刚刚通过的列表)。

您的原始 foo 带有默认参数,不应修改 a 是否已明确传递或获得默认值。您的代码应仅留下可变的参数,除非从上下文/名称/文档清楚地表明应该修改这些参数。无论我们是在Python中,是否涉及默认参数,使用作为本地临时性作为本地临时性作为本地临时性的参数是一个非常糟糕的主意。

如果您需要在计算某些内容的过程中破坏性地操纵本地临时性,并且需要从参数值开始操纵,则需要制作副本。

This actually has nothing to do with default values, other than that it often comes up as an unexpected behaviour when you write functions with mutable default values.

>>> def foo(a):
    a.append(5)
    print a

>>> a  = [5]
>>> foo(a)
[5, 5]
>>> foo(a)
[5, 5, 5]
>>> foo(a)
[5, 5, 5, 5]
>>> foo(a)
[5, 5, 5, 5, 5]

No default values in sight in this code, but you get exactly the same problem.

The problem is that foo is modifying a mutable variable passed in from the caller, when the caller doesn't expect this. Code like this would be fine if the function was called something like append_5; then the caller would be calling the function in order to modify the value they pass in, and the behaviour would be expected. But such a function would be very unlikely to take a default argument, and probably wouldn't return the list (since the caller already has a reference to that list; the one it just passed in).

Your original foo, with a default argument, shouldn't be modifying a whether it was explicitly passed in or got the default value. Your code should leave mutable arguments alone unless it is clear from the context/name/documentation that the arguments are supposed to be modified. Using mutable values passed in as arguments as local temporaries is an extremely bad idea, whether we're in Python or not and whether there are default arguments involved or not.

If you need to destructively manipulate a local temporary in the course of computing something, and you need to start your manipulation from an argument value, you need to make a copy.

&quot“至少惊讶”和可变的默认论点

暖阳 2025-02-19 15:54:22

位置:粘性不执行您认为做的事情。向下滚动时,它将使元素粘在标头上。

您可以使用flexbox或网格将元素粘在底部。

例如,在此处查看:

flexbox: https://dev.to/nehalahmadkhan/how-to-make-foot-foot-------------------------------------page-3i14

grid:在底部使用CSS网格的页脚?无法弄清楚吗?

只是要知道,在某些旧手机上, 100VH 可能是一个问题 - 由于未计算的额外标头间距。

位置粘性如果您必须支持IE11,则不起作用。

The position: sticky does not do what you think it does. It will make the element stick to the header when you scroll down.

You can use either flexbox or grid to make the element stick to the bottom.

For example, have a look here:

flexbox: https://dev.to/nehalahmadkhan/how-to-make-footer-stick-to-bottom-of-web-page-3i14

grid: Footer at bottom with css grid? Can't figure it out?

Just be aware, that on some older phones the 100vh may be an issue - due to the extra header-spacing that is not calculated.

position sticky does not work on IE11, if you have to support that.

底部的粘性位置:0不起作用

暖阳 2025-02-18 20:51:47

查看 docs > REGEX 参数默认为 true ,因此它将管道字符解释为脱节操作员,而不是字面的管道。

只需设置 regex = false 即可修复以下内容:

>>> print(df.loc[df['A'].str.contains('|', regex=False)])
           A      B
1  bbb | aaa  a | b

Looking at the docs, the regex argument defaults to True, so it is interpreting the pipe character as a disjunction operator, not a literal pipe.

Simply set regex=False to fix this:

>>> print(df.loc[df['A'].str.contains('|', regex=False)])
           A      B
1  bbb | aaa  a | b

df.col.str.contains(somester&#x27;)d没有工作

暖阳 2025-02-18 17:31:42

重新格式对于这样的工作来说是整洁的。在匿名函数中定义一个迭代的过程(具有函数(x)或缩写> \(x))的过程,然后将其放入 lapply 摘要可以像使用相应的列名称中的数据框那样,将其子集属于所需列。

让我们在一个示例中使用 nhanes 数据包含 MICE

dvs <- c('age1', 'age2', 'age3')

res <- lapply(dvs, \(x) {
  mi <- with(imp, glm(reformulate(c('bmi', 'hyp', 'chl'), x), family=binomial))
  s <- summary(pool(mi), exponentiate=TRUE, conf.int=TRUE)
  `rownames<-`(s[c('estimate', '2.5 %', '97.5 %')], s$term) |> as.matrix()
}) |> setNames(dvs)

了这样的命名列表,

res
# $age1
#                 estimate     2.5 %   97.5 %
# (Intercept) 2.197201e+04 0.0000000      Inf
# bmi         1.999346e+00 0.4691464 8.520549
# hyp         4.331347e-08 0.0000000      Inf
# chl         9.441578e-01 0.8403936 1.060734
# 
# $age2
#              estimate        2.5 %      97.5 %
# (Intercept) 0.9300514 0.0002224722 3888.105740
# bmi         0.8891490 0.6550513927    1.206907
# hyp         2.8818840 0.2054892623   40.416981
# chl         1.0046189 0.9757483655    1.034344
# 
# $age3
#              estimate        2.5 %       97.5 %
# (Intercept) 3.5383401 1.087542e-07 1.151206e+08
# bmi         0.6442681 2.792523e-01 1.486403e+00
# hyp         5.9651279 5.954159e-02 5.976117e+02
# chl         1.0323994 9.885890e-01 1.078151e+00

您可以以这种方式输出单个元素:

res$age1
#                 estimate     2.5 %   97.5 %
# (Intercept) 2.197201e+04 0.0000000      Inf
# bmi         1.999346e+00 0.4691464 8.520549
# hyp         4.331347e-08 0.0000000      Inf
# chl         9.441578e-01 0.8403936 1.060734

这给出

class(res$age1)
# [1] "matrix" "array" 

如果您想要类“ data.frame” 在列表元素中,只需删除 |&gt ; as.matrix()零件。


数据:

data("nhanes", package='mice')
nhanes <- transform(nhanes, age1=age == 1, age2=age == 2, age3=age == 3)
library(mice)
imp0 <- mice(nhanes, maxit=0)
imp <- mice(nhanes, maxit=5, 
            predictorMatrix=imp0$predictorMatrix,
            method=imp0$method, print=F)

reformulate is neat for jobs like this. Define the process of one iteration in an anonymous function (those with function(x) or abbreviated \(x)) and put it into lapply. The summary can be subsetted to desired columns just like a data frame using the respective column names in brackets.

Let's use the nhanes data coming with mice in an example.

dvs <- c('age1', 'age2', 'age3')

res <- lapply(dvs, \(x) {
  mi <- with(imp, glm(reformulate(c('bmi', 'hyp', 'chl'), x), family=binomial))
  s <- summary(pool(mi), exponentiate=TRUE, conf.int=TRUE)
  `rownames<-`(s[c('estimate', '2.5 %', '97.5 %')], s$term) |> as.matrix()
}) |> setNames(dvs)

This gives a named list like this one,

res
# $age1
#                 estimate     2.5 %   97.5 %
# (Intercept) 2.197201e+04 0.0000000      Inf
# bmi         1.999346e+00 0.4691464 8.520549
# hyp         4.331347e-08 0.0000000      Inf
# chl         9.441578e-01 0.8403936 1.060734
# 
# $age2
#              estimate        2.5 %      97.5 %
# (Intercept) 0.9300514 0.0002224722 3888.105740
# bmi         0.8891490 0.6550513927    1.206907
# hyp         2.8818840 0.2054892623   40.416981
# chl         1.0046189 0.9757483655    1.034344
# 
# $age3
#              estimate        2.5 %       97.5 %
# (Intercept) 3.5383401 1.087542e-07 1.151206e+08
# bmi         0.6442681 2.792523e-01 1.486403e+00
# hyp         5.9651279 5.954159e-02 5.976117e+02
# chl         1.0323994 9.885890e-01 1.078151e+00

where you can output individual elements in this way:

res$age1
#                 estimate     2.5 %   97.5 %
# (Intercept) 2.197201e+04 0.0000000      Inf
# bmi         1.999346e+00 0.4691464 8.520549
# hyp         4.331347e-08 0.0000000      Inf
# chl         9.441578e-01 0.8403936 1.060734

Where

class(res$age1)
# [1] "matrix" "array" 

If you want class "data.frame" in the list elements, just leave out the |> as.matrix() part.


Data:

data("nhanes", package='mice')
nhanes <- transform(nhanes, age1=age == 1, age2=age == 2, age3=age == 3)
library(mice)
imp0 <- mice(nhanes, maxit=0)
imp <- mice(nhanes, maxit=5, 
            predictorMatrix=imp0$predictorMatrix,
            method=imp0$method, print=F)

使用多个插补数据集为逻辑回归中的多个因变量创建循环?

暖阳 2025-02-18 04:38:11
void MainWindow::buildWindow(Level *level, GraphicalUI *graphicUI) {
    QGridLayout* layout = new QGridLayout(this);
}

那就是解决方案。
该函数也是所需的在类的标题中存在。

void MainWindow::buildWindow(Level *level, GraphicalUI *graphicUI) {
    QGridLayout* layout = new QGridLayout(this);
}

Thats the solution.
The function is also required to exist in the header of the class.

在构造函数之外使用它

暖阳 2025-02-18 03:49:01

假设variadic参数列表中的所有项目均为相同的类型,那么您可以使用此技巧:

将实际函数实现为非variadic的函数,占据数组和大小。以及任意数量的非广播论点。示例:

void actual_func (int this, double that, size_t argc, int argv[argc])
{
  printf("this:%d that:%f\n", this, that);
  for(size_t i=0; i<argc; i++)
    printf("%d ", argv[i]);
}

此处 可以是任何类型的任何参数,与示例中的固定参数相对应。 argc argv 分别是大小和数组。

然后,我们可以编写一个variadic宏来将variadic调用转换为一个普通函数调用:

#define COUNT_ARGS(...) ( sizeof((int[]){__VA_ARGS__}) / sizeof(int) )
#define func(this,that,...) actual_func(this, that, COUNT_ARGS(__VA_ARGS__), (int[]){__VA_ARGS__})

辅助宏 count_args 计算variadic项目的数量 - 它们都必须是 int 或它行不通。这给出了数组大小。然后,以变色的参数初始化了以复合文字形式的临时数组,然后传递给该函数。完整的示例:

#include <stdio.h>

void actual_func (int this, double that, size_t argc, int argv[argc])
{
  printf("this:%d that:%f\n", this, that);
  for(size_t i=0; i<argc; i++)
    printf("%d ", argv[i]);
}

#define COUNT_ARGS(...) ( sizeof((int[]){__VA_ARGS__}) / sizeof(int) )
#define func(this,that,...) actual_func(this,that,COUNT_ARGS(__VA_ARGS__),(int[]){__VA_ARGS__})

int main (void) 
{
  func(1, 1.0f, 1, 2, 3);
}

这与整数分配具有相同的类型安全性,含义是SO-SO,但它比Variadic函数更安全。

Assuming all items in the variadic argument list are of the same type, then you can use this trick:

Implement the actual function as a non-variadic one, taking an array and size. As well as any number of non-variadic arguments. Example:

void actual_func (int this, double that, size_t argc, int argv[argc])
{
  printf("this:%d that:%f\n", this, that);
  for(size_t i=0; i<argc; i++)
    printf("%d ", argv[i]);
}

Here this and that can be any parameters of any type, corresponding to the fixed parameters in your examples. The argc and argv is the size and array respectively.

We can then write a variadic macro to translate the variadic call into a plain function call:

#define COUNT_ARGS(...) ( sizeof((int[]){__VA_ARGS__}) / sizeof(int) )
#define func(this,that,...) actual_func(this, that, COUNT_ARGS(__VA_ARGS__), (int[]){__VA_ARGS__})

The helper macro COUNT_ARGS counts the number of variadic items - they all have to be int or it won't work. This gives the array size. Then a temporary array in the form of a compound literal is initialized with the variadic arguments, then passed to the function. Full example:

#include <stdio.h>

void actual_func (int this, double that, size_t argc, int argv[argc])
{
  printf("this:%d that:%f\n", this, that);
  for(size_t i=0; i<argc; i++)
    printf("%d ", argv[i]);
}

#define COUNT_ARGS(...) ( sizeof((int[]){__VA_ARGS__}) / sizeof(int) )
#define func(this,that,...) actual_func(this,that,COUNT_ARGS(__VA_ARGS__),(int[]){__VA_ARGS__})

int main (void) 
{
  func(1, 1.0f, 1, 2, 3);
}

This has the same type safety as integer assignment, meaning so-so, but it is way safer than variadic functions.

如何编写包装C variadic函数的动态加载程序?

暖阳 2025-02-17 21:12:28

我找到了一个简洁的解决方案,可以删除@updatetimestamp和@lastmodified by注释,并使用

有关如何创建@preupdate钩以设置修饰符值的示例:

@PreUpdate
public void edit() {
    AppUserPrincipal user = AuthUtils.getCurrentUser();
    this.setLastModifiedDate(LocalDateTime.now());
    this.setLastModifiedBy(user.getUserId());
}

I found a neat solution to remove @UpdateTimestamp and @LastModifiedBy annotations, and use JPA Entity Lifecycle events.

Example on how I created my @PreUpdate hook to set modifier values:

@PreUpdate
public void edit() {
    AppUserPrincipal user = AuthUtils.getCurrentUser();
    this.setLastModifiedDate(LocalDateTime.now());
    this.setLastModifiedBy(user.getUserId());
}

如何在创建新实体时将@lastmodifiedby字段保持空(null),仅在更新上设置

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文