[旋木]

文章 评论 浏览 30

[旋木] 2025-02-16 08:54:37

较短的选择是:

export const store = configureStore({
    reducer: persistedReducer,
    middleware: (getDefaultMiddleware) => {
      let middleware = getDefaultMiddleware({
        serializableCheck: false,
      });

      if (process.env.NODE_ENV == "development") {
        middleware = middleware.concat(logger);
      }
      return middleware;
    }

  });

The somewhat shorter option would be:

export const store = configureStore({
    reducer: persistedReducer,
    middleware: (getDefaultMiddleware) => {
      let middleware = getDefaultMiddleware({
        serializableCheck: false,
      });

      if (process.env.NODE_ENV == "development") {
        middleware = middleware.concat(logger);
      }
      return middleware;
    }

  });

有条件地添加logger时,使用Redux工具包的GetDefaultMiddleware有错误

[旋木] 2025-02-15 21:14:07

运行


public class MyClass
 
    public shared event SomeEvent As EventHandler
    
    private sub New()
    end sub

    public shared sub CreateInstance()
        Dim instance as new MyClass()
        RaiseEvent SomeEvent(instance, new EventArgs())
        return instance;
    End Sub

end class

AddHandler MyClass.SomeEvent, AddressOf SomeHandlerMethod

dim cls as MyClass = MyClass.CreateInstance()

解决方案 -在获得 cls 之前,使用共享事件的工厂方法 somehandlermethod

Solution - use a factory method with shared event


public class MyClass
 
    public shared event SomeEvent As EventHandler
    
    private sub New()
    end sub

    public shared sub CreateInstance()
        Dim instance as new MyClass()
        RaiseEvent SomeEvent(instance, new EventArgs())
        return instance;
    End Sub

end class

Consume

AddHandler MyClass.SomeEvent, AddressOf SomeHandlerMethod

dim cls as MyClass = MyClass.CreateInstance()

SomeHandlerMethod will run before you get cls

您如何创建“启动”类“类”事件还是有一个?

[旋木] 2025-02-15 16:35:11
var v1 = await 
db.collection('persons').find(where.list(['firstName','lastName']);
var v1 = await 
db.collection('persons').find(where.list(['firstName','lastName']);

如何在Dart Mongo DB驱动程序中使用投影

[旋木] 2025-02-15 08:37:06

此IF语句

if(_char_array[0] != '\0') {...}

检查字符数组是否包含非空字符串。

实际上,比较了两个整数:数组的第一个字符 _CHAR_ARRAY 升级为 int 和整数字符常数'\ 0'它具有类型 int

该语句也可以像一样重写

if( _char_array[0] ) {...}

,也

if( *_char_array ) {...}

可以这样做,如果语句

if(_char_array != '\0') {...}

没有意义,因为任何数组都占据了内存范围。因此,将其转换为指针转换为第一个元素,它不能成为无效的指针。

那就是在此语句中,由于数组的隐式转换为指向其第一个元素的指针和无效的指针常数,因此可以比较到数组的第一个元素的指针。

如果 _Char_Array 最初声明为指针,则上述IF语句检查指针是否不是零指针。

该声明可以像

if( _char_array ) {...}

This if statement

if(_char_array[0] != '\0') {...}

checks whether a character array contains a non-empty string.

In fact there are compared two integers: the first character of the array _char_array promoted to the type int and the integer character constant '\0' that has the type int.

The statement can be rewritten also like

if( _char_array[0] ) {...}

or

if( *_char_array ) {...}

This if statement

if(_char_array != '\0') {...}

does not make a sense because any array occupies a memory extent. So converted to a pointer to its first element it can not be a null pointer.

That is in this statement there are compared a pointer to the first element of the array due to the implicit conversion of the array to a pointer to its first element and a null pointer constant.

If _char_array is initially declared as a pointer then the above if statement checks whether the pointer is not a null pointer.

The statement can be rewritten like

if( _char_array ) {...}

空char阵列,我检查的方式是相同的吗?

[旋木] 2025-02-15 06:15:25

因为 false =='';

这样做以打印布尔值:

$bool = false;
echo $bool ? 'true' : 'false';

或...

echo $bool ? 'yes' : 'no';
echo $bool ? '1' : '0';

Because false == '';

do this to print booleans:

$bool = false;
echo $bool ? 'true' : 'false';

or...

echo $bool ? 'yes' : 'no';
echo $bool ? '1' : '0';

为什么不这样/php打印true/false?

[旋木] 2025-02-14 16:01:11

使用 parent> parent> parent> parent> parentnode 循环到回溯父节点。简而言之:

let par = document.querySelector("p");
let path = "";

while ( par.parentNode && par.tagName && "HTML" !== par.tagName ) {
  path = par.tagName + (("" !== path)? " > " + path: "");
  par = par.parentNode;
}

一个说明:迭代父母节点 - 雷神顶部将返回未定义并退出循环。如果找到父,并且具有 tagName 值,并且不是顶部元素,则HTML,然后继续将 tagName to path 变量,包括a 路径是一个空字符串。

...和工作示例:

let par = document.querySelector("p");
let path = "";

// loop parent nodes of provided element, making sure each has a tagName, and is not the HTML tag
while ( par.parentNode && par.tagName && "HTML" !== par.tagName ) {

  // prepend the tagName to the path variable
                       // don't write the child combinator on first iteration
  path = par.tagName + (("" !== path)? " > " + path: "");

  // get next parent
  par = par.parentNode;
}
console.log(path);
<div>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</div>

Using parentNode and while loop to backtrack parent nodes. In brief:

let par = document.querySelector("p");
let path = "";

while ( par.parentNode && par.tagName && "HTML" !== par.tagName ) {
  path = par.tagName + (("" !== path)? " > " + path: "");
  par = par.parentNode;
}

An explanation: iterate over the parent nodes—reaching top will return undefined and exit the loop. If a parent is found, and it has a tagName value, and it is not the top element, HTML, then proceed with prepending the tagName to the path variable, including a child combinator as a separator. Don't include the separator on the first iteration because path is an empty string.

...and working example:

let par = document.querySelector("p");
let path = "";

// loop parent nodes of provided element, making sure each has a tagName, and is not the HTML tag
while ( par.parentNode && par.tagName && "HTML" !== par.tagName ) {

  // prepend the tagName to the path variable
                       // don't write the child combinator on first iteration
  path = par.tagName + (("" !== path)? " > " + path: "");

  // get next parent
  par = par.parentNode;
}
console.log(path);
<div>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</div>

通过搜索从字符串中获取HTML选择器的方法

[旋木] 2025-02-14 13:34:53

最后,我解决了这个问题,

而不是使用@before建议使用的@around建议,而应使用consge方法返回对象。

@Aspect   
@Component   
public class AOPExample {

   @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping) ||"
        + "@annotation(org.springframework.web.bind.annotation.PostMapping)")
   public void controllerRequestMapping() {}

   @Around("controllerRequestMapping()")
   public Object advice(ProceedingJoinPoint jp) throws Throwable {
    
         HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
            .getRequest();
         String header = request.getHeader("application-name");
         System.out.println("Header in AOP"+header);
         if (header == null) {
              HttpServletRequestWrapperClass wrappedRequest = new HttpServletRequestWrapperClass(request);
              wrappedRequest.putHeader("application-name", "Unknown");
              request = wrappedRequest;
        } else {
            //validate application name
            //400 - throw bad request exception
            //throw new BadRequestException("Invalid application name");
        }
        System.out.println("After setting---"+request.getHeader("application-name"));
        return jp.proceed(new Object[] {request});
    }
}

更新的Httpservlet请求正在使用控制器方法。谢谢

Finally I resolved the issue,

Instead of using @Before advice used @Around advice, Around advice should return the object using proceed method.

@Aspect   
@Component   
public class AOPExample {

   @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping) ||"
        + "@annotation(org.springframework.web.bind.annotation.PostMapping)")
   public void controllerRequestMapping() {}

   @Around("controllerRequestMapping()")
   public Object advice(ProceedingJoinPoint jp) throws Throwable {
    
         HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
            .getRequest();
         String header = request.getHeader("application-name");
         System.out.println("Header in AOP"+header);
         if (header == null) {
              HttpServletRequestWrapperClass wrappedRequest = new HttpServletRequestWrapperClass(request);
              wrappedRequest.putHeader("application-name", "Unknown");
              request = wrappedRequest;
        } else {
            //validate application name
            //400 - throw bad request exception
            //throw new BadRequestException("Invalid application name");
        }
        System.out.println("After setting---"+request.getHeader("application-name"));
        return jp.proceed(new Object[] {request});
    }
}

Updated httpservlet request is getting in controller method. Thanks

如何从aop @before到spring Controller方法的建议获取更新/修改的httpservletrequest对象

[旋木] 2025-02-13 19:11:19

按订单ID添加最大总数(或最低或平均)订单日期。

转到 报告的菜单选项,小组排序专家...
并按照整个组对组进行分类。

Add a group total of Maximum (or minimum, or Average) Order Date by Order ID.

Go to the menu option of Report, Group Sort Expert...
and sort the groups by that total.

水晶报告:按一个字段组成,按另一个领域排序

[旋木] 2025-02-13 19:03:50

如果

let showMenu = (!p.currentUser || p.currentUser.getValue('id') === 7) ? false : true;

您想使用承诺,可以

function validateMenu() {
    return new Promises((resolve, reject) => {

        if (!p.currentUser || p.currentUser.getValue('id') === 7) {
            resolve(false)
        } else {
            resolve(true)
        }
    });
}

It's

let showMenu = (!p.currentUser || p.currentUser.getValue('id') === 7) ? false : true;

If you want to use promises you can

function validateMenu() {
    return new Promises((resolve, reject) => {

        if (!p.currentUser || p.currentUser.getValue('id') === 7) {
            resolve(false)
        } else {
            resolve(true)
        }
    });
}

js将函数转换为一行,而没有/else

[旋木] 2025-02-13 14:25:48

Ecmascript 6具有“发电机”,可让您轻松地以异步风格进行编程。

function* myGenerator() {
    const callback = yield;
    let [response] = yield $.ajax("https://stackoverflow.com", {complete: callback});
    console.log("response is:", response);

    // examples of other things you can do
    yield setTimeout(callback, 1000);
    console.log("it delayed for 1000ms");
    while (response.statusText === "error") {
        [response] = yield* anotherGenerator();
    }
}

要运行上述代码,您要这样做:

const gen = myGenerator(); // Create generator
gen.next(); // Start it
gen.next((...args) => gen.next([...args])); // Set its callback function

如果您需要定位不支持ES6的浏览器,则可以通过babel或closure-compiler运行代码以生成ecmascript 5。

呼叫 ... args 在阅读时,被包裹在数组中并破坏,以便模式可以应对具有多个参数的回调。例如,使用 node fs fs

const [err, data] = yield fs.readFile(filePath, "utf-8", callback);

ECMAScript 6 has 'generators' which allow you to easily program in an asynchronous style.

function* myGenerator() {
    const callback = yield;
    let [response] = yield $.ajax("https://stackoverflow.com", {complete: callback});
    console.log("response is:", response);

    // examples of other things you can do
    yield setTimeout(callback, 1000);
    console.log("it delayed for 1000ms");
    while (response.statusText === "error") {
        [response] = yield* anotherGenerator();
    }
}

To run the above code you do this:

const gen = myGenerator(); // Create generator
gen.next(); // Start it
gen.next((...args) => gen.next([...args])); // Set its callback function

If you need to target browsers that don't support ES6 you can run the code through Babel or closure-compiler to generate ECMAScript 5.

The callback ...args are wrapped in an array and destructured when you read them so that the pattern can cope with callbacks that have multiple arguments. For example with node fs:

const [err, data] = yield fs.readFile(filePath, "utf-8", callback);

如何从异步电话中返回响应?

[旋木] 2025-02-12 19:11:30
var date_today=new Date();
var formated_date = formatDate(date_today);//Calling formatDate Function

var input_date="2015/04/22 11:12 AM";

var currentDateTime = new Date(Date.parse(formated_date));
var inputDateTime   = new Date(Date.parse(input_date));

if (inputDateTime <= currentDateTime){
    //Do something...
}

function formatDate(date) {
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var ampm = hours >= 12 ? 'PM' : 'AM';

    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    hours   = hours < 10 ? '0'+hours : hours ;

    minutes = minutes < 10 ? '0'+minutes : minutes;

    var strTime = hours+":"+minutes+ ' ' + ampm;
    return  date.getFullYear()+ "/" + ((date.getMonth()+1) < 10 ? "0"+(date.getMonth()+1) :
    (date.getMonth()+1) ) + "/" + (date.getDate() < 10 ? "0"+date.getDate() :
    date.getDate()) + " " + strTime;
}
var date_today=new Date();
var formated_date = formatDate(date_today);//Calling formatDate Function

var input_date="2015/04/22 11:12 AM";

var currentDateTime = new Date(Date.parse(formated_date));
var inputDateTime   = new Date(Date.parse(input_date));

if (inputDateTime <= currentDateTime){
    //Do something...
}

function formatDate(date) {
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var ampm = hours >= 12 ? 'PM' : 'AM';

    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    hours   = hours < 10 ? '0'+hours : hours ;

    minutes = minutes < 10 ? '0'+minutes : minutes;

    var strTime = hours+":"+minutes+ ' ' + ampm;
    return  date.getFullYear()+ "/" + ((date.getMonth()+1) < 10 ? "0"+(date.getMonth()+1) :
    (date.getMonth()+1) ) + "/" + (date.getDate() < 10 ? "0"+date.getDate() :
    date.getDate()) + " " + strTime;
}

将两个日期与JavaScript进行比较

[旋木] 2025-02-12 12:03:19

您可以将其写入文本文件/或外部文件。然后从JavaScript读取该文件。然后使用JS更新您的HTML页面。

另一个选项是制作烧瓶/Django服务器,并设置一个迷你后端,然后设置一个将返回Python中数据的GET请求。
然后可以通过JavaScript中的“获取”函数来获取此功能,再次更新您的HTML页面。

希望这有帮助!

You could write it to a text file/ or an external file. And then read that file from javascript. Then use the JS to update your HTML page.

Another option would be to make a flask/django server, and setup a mini backend, and then setup a get request that will return the data in python.
This can then be fetched by the "fetch" function in javascript, once again updating your HTML page.

Hope this helps!

Python中计算时间为HTML中的变量的结果

[旋木] 2025-02-12 11:52:25

1。对于其他许多人来说,这是第一个绊脚石

,我与异步电话的相遇起初令人困惑。
我不记得细节,但我可能尝试了类似的事情:

let result;

$.ajax({
  url: 'https://jsonplaceholder.typicode.com/todos/1',
  success: function (response) {
    console.log('\nInside $.ajax:');
    console.log(response);
    result = response;
  },
});

console.log('Finally, the result: ' + result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

whops!
线的输出
console.log('最后,结果:' +结果);
我认为将在另一个输出之前打印出上次
- 并且它不包含结果:它只是打印未定义的 1
怎么会?

一个有用的见解,

我清楚地记得我的第一个 aha

1. A first stumbling step

As for many others, my encounter with asynchronous calls was puzzling at first.
I don't remember the details, but I may have tried something like:

let result;

$.ajax({
  url: 'https://jsonplaceholder.typicode.com/todos/1',
  success: function (response) {
    console.log('\nInside $.ajax:');
    console.log(response);
    result = response;
  },
});

console.log('Finally, the result: ' + result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Whoops!
The output of the line
console.log('Finally, the result: ' + result);
which I thought would be printed last, is printed before the other output!
– And it doesn't contain the result: it just prints undefined. 1
How come?

A helpful insight

I distinctly remember my first aha (????) moment about asynchronous calls.
It was :

you actually don't want to get the data out of a callback; you want to get your data-needing action into the callback!
2

This is true in the example above.

2. Plain JavaScript and a callback function

Luckily, it is possible to write code after the asynchronous call that deals with the response once it has completed.

One alternative is the use of a callback function in a continuation-passing style :
3

const url = 'https://jsonplaceholder.typicode.com/todos/2';

function asynchronousFunc(callback) {
  const request = new XMLHttpRequest();
  request.open('GET', url);
  request.send();
  request.onload = function () {
    if (request.readyState === request.DONE) {
      console.log('The request is done. Now calling back.');
      callback(request.responseText);
    }
  };
}

asynchronousFunc(function (result) {
  console.log('This is the start of the callback function. Result:');
  console.log(result);
  console.log('The callback function finishes on this line. THE END!');
});

console.log('LAST in the code, but executed FIRST!');
.as-console-wrapper { max-height: 100% !important; top: 0; }

Note how the function asynchronousFunc is void. It returns nothing.
asynchronousFunc is called with an anonymous callback function,
(asynchronousFunc(function (result) {...});).
This executes the desired actions on the result after the request has completed – when the responseText is available.

Running the above snippet shows how I will probably not want to write any code after the asynchronous call (such as the line
LAST in the code, but executed FIRST!).
Why? – Because such code will run before the asynchronous call delivers any response data.
Doing so is bound to cause confusion when comparing the code with the output.

3. Promise with .then()

The .then() construct was introduced in the ECMA-262 6th Edition in June 2015.
The code below is plain JavaScript, replacing the old-school XMLHttpRequest with Fetch. 4

fetch('https://api.chucknorris.io/jokes/random')
  .then((response) => response.json())
  .then((responseBody) => {
    console.log('Using .then() :');
    console.log(responseBody.value + '\n');
  });
.as-console-wrapper { max-height: 100% !important; top: 0; }

4. Promise with async/await

The async/await construct was introduced in the ECMA-262 8th Edition in June 2017.

async function awaitAndReceivePromise() {
  const responseBody = (
    await fetch('https://api.quotable.io/quotes/random')
  ).json();
  console.log('Using async/await:');
  const obj = (await responseBody)[0];
  console.log('"' + obj.content + '" – ' + obj.author + '\n');
}

awaitAndReceivePromise();
.as-console-wrapper { max-height: 100% !important; top: 0; }

A word of warning is warranted if you decide to go with the async/await construct.
Note in the above snippet how await is needed in two places.
If forgotten in the first place, there will be no output at all.
If forgotten in the second place, the only output will be Using async/await: – nothing else gets printed.
Forgetting the async prefix of the function is maybe the worst of all – you'll get a "SyntaxError" – and likely no hint about the missing async keyword.


All the above examples succinctly convey how asynchronous calls may be used on toyish APIs. 5

References


1
Expressed by the asker of the question as they all return undefined.

2
Here is more on how asynchronous calls may be confusing at first.

3
Like the X in AJAX, the name XMLHttpRequest is misleading – it can be used to retrieve any type of data, not just XML.
These days, the data format of Web APIs is ubiquitously JSON, not XML.

4
Fetch returns a Promise.
I was surprised to learn that neither XMLHttpRequest nor Fetch are part of the ECMAScript standard.
The reason JavaScript can access them here is that the web browser provides them.
The Fetch Standard and the XMLHttpRequest Standard are both upheld by the Web Hypertext Application Technology Working Group which was formed in June 2004. \

5
You might also be interested in
How can I fetch an array of URLs with Promise.all?.

如何从异步电话中返回响应?

[旋木] 2025-02-12 06:07:39

将两个设置定义为表,并在PowerQuery中定义“左联接”。在那里您可以选择结果表的列。

https://lealen.microsoft.com/en-comrosoft.com/en-en-en-en-en-en-en-en-en-en-n-come美国/电力/Query/Merge-Queries-Left-outer

Define both sets as tables and “left join” in PowerQuery. There you can choose the columns of the resulting table.

https://learn.microsoft.com/en-us/power-query/merge-queries-left-outer

Excel合并两张桌子

[旋木] 2025-02-11 18:09:47

将频率切成原始值的1/4,如 @demo12提出了所提出的OP的问题。可能值得考虑一个稍有不同的问题。给定频率表,您能否通过对原始数据进行子采样来探索不同样本量的含义吗?

obs.df <- as.data.frame.table(obs.tab) # Convert table to data frame
idx <- rep.int(1:9, times=obs.df$Freq) # Convert data frame to long data frame
obs.long <- obs.df[idx, 1:2]
names(obs.long) <- c("Species", "Size")
rownames(obs.long) <- NULL
str(obs.long)
# 'data.frame': 150 obs. of  2 variables:
#  $ Species: Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
#  $ Size   : Factor w/ 3 levels "small","medium",..: 1 1 1 1 1 1 1 1 1 1 ...

这将表转换为数据框,以识别150个观测值中的每个物种和大小。现在,我们从该数据框架中采样:

obs.samp <- table(bs.long[sample.int(150, 38), ]) # Draw a sample of 150/4 observations
obs.samp
#             Size
# Species      small medium large
#   setosa        10      2     0
#   versicolor     4     11     0
#   virginica      0      8     3
fisher.test(obs.samp)
# 
#   Fisher's Exact Test for Count Data
# 
# data:  obs.samp
# p-value = 3.908e-05
# alternative hypothesis: two.sided

每次运行该代码时,您都会获得38个观测值的不同随机样本。

Cutting the frequencies to 1/4 of the original values as @Demo12 suggests answers the OP's question as posed. It may be worth considering a slightly different question. Given a table of frequencies, can you explore the implications of different sample sizes by sub-sampling the original data?

obs.df <- as.data.frame.table(obs.tab) # Convert table to data frame
idx <- rep.int(1:9, times=obs.df$Freq) # Convert data frame to long data frame
obs.long <- obs.df[idx, 1:2]
names(obs.long) <- c("Species", "Size")
rownames(obs.long) <- NULL
str(obs.long)
# 'data.frame': 150 obs. of  2 variables:
#  $ Species: Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
#  $ Size   : Factor w/ 3 levels "small","medium",..: 1 1 1 1 1 1 1 1 1 1 ...

This converts the table into a data frame identifying the Species and Size for each of the 150 observations. Now we sample from that data frame:

obs.samp <- table(bs.long[sample.int(150, 38), ]) # Draw a sample of 150/4 observations
obs.samp
#             Size
# Species      small medium large
#   setosa        10      2     0
#   versicolor     4     11     0
#   virginica      0      8     3
fisher.test(obs.samp)
# 
#   Fisher's Exact Test for Count Data
# 
# data:  obs.samp
# p-value = 3.908e-05
# alternative hypothesis: two.sided

Each time this code is run, you get a different random sample of 38 observations.

Fisher测试警告

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

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