问:
Using async-await not returning the values
I use the following code which works! I was able to fetch the data in the spread (then) , http200

```<code>Promise.all([
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'run:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    }),
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'exe:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    })
  ]).then(axios.spread((...responses: AxiosResponse[]) => {
      const aToken = responses[0];
      const bToken = responses[1];
    }).catch(function(error: any) {
      console.log("Error: " + error);
    });
</code>```

Now I want to wrap it with async function which return two response (responses[0], responses[1] )

I’ve created this function

```<code>const FetchData = async (): Promise<{ run: string; app: string }> => {

let aToken:string;
let bToken:string;
Promise.all([
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'run:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    }),
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'exe:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    })
  ]).then(axios.spread((...responses: AxiosResponse[]) => {
      aToken = responses[0];
      bToken = responses[1];
    }).catch(function(error: any) {
      console.log("Error: " + error);
    });

// add this return
return {
    run: aToken ,
    app: bToken
};

)}
</code>```

Now I’ve created function to call it and get the tokens

```<code>async function main() {

    let val = await FetchData();
    console.log(val)

}
</code>```

The problem is that I got empty value in the val property, while put a breakpoint inside main function
I see that I got into the console, before I actually get the values from the ).then(axios.spread(( ,
Any idea how to adopt the code to return the value from the spread operator and then call to the console?

答:
You are not using async-await correctly. You need to await Promise.all. Once both promises are resolved, response data will be in a property named data inside each response object that you get from axios. If you need whole response object then you can destructure it

Here's an example

```<code>const FetchData = async (): Promise<{ run: string; app: string }> => {
    try {
        const [response1, response2] = await Promise.all([
            axios({
               ...
            }),
            axios({
               ...
            })
        ]);

        return {
          run: response1,
          app: response2
        };

   } catch (error) {
      console.log(error);
   }
};
</code>```

Here's a demo that fetches data from 2 endpoints of jsonplaceholder api

Body:
I use the following code which works! I was able to fetch the data in the spread (then) , http200

Promise.all([
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'run:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    }),
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'exe:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    })
  ]).then(axios.spread((...responses: AxiosResponse[]) => {
      const aToken = responses[0];
      const bToken = responses[1];
    }).catch(function(error: any) {
      console.log("Error: " + error);
    });

Now I want to wrap it with async function which return two response (responses[0], responses[1] )

I’ve created this function

const FetchData = async (): Promise<{ run: string; app: string }> => {

let aToken:string;
let bToken:string;
Promise.all([
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'run:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    }),
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'exe:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    })
  ]).then(axios.spread((...responses: AxiosResponse[]) => {
      aToken = responses[0];
      bToken = responses[1];
    }).catch(function(error: any) {
      console.log("Error: " + error);
    });

// add this return
return {
    run: aToken ,
    app: bToken
};

)}

Now I’ve created function to call it and get the tokens

async function main() {

    let val = await FetchData();
    console.log(val)

}

The problem is that I got empty value in the val property, while put a breakpoint inside main function
I see that I got into the console, before I actually get the values from the ).then(axios.spread(( ,
Any idea how to adopt the code to return the value from the spread operator and then call to the console?

Body:
You are not using async-await correctly. You need to await Promise.all. Once both promises are resolved, response data will be in a property named data inside each response object that you get from axios. If you need whole response object then you can destructure it

Here's an example

const FetchData = async (): Promise<{ run: string; app: string }> => {
    try {
        const [response1, response2] = await Promise.all([
            axios({
               ...
            }),
            axios({
               ...
            })
        ]);

        return {
          run: response1,
          app: response2
        };

   } catch (error) {
      console.log(error);
   }
};

Here's a demo that fetches data from 2 endpoints of jsonplaceholder api


来源: stackexchange

问:
Most efficient way in Python to iterate over a large file (10GB+)
I'm working on a Python script to go through two files - one containing a list of UUIDs, the other containing a large amount of log entries - each line containing one of the UUIDs from the other file. The purpose of the program is to create a list of the UUIDS from file1, then for each time that UUID is found in the log file, increment the associated value for each time a match is found.

So long story short, count how many times each UUID appears in the log file.
At the moment, I have a list which is populated with UUID as the key, and 'hits' as the value. Then another loop which iterates over each line of the log file, and checking if the UUID in the log matches a UUID in the UUID list. If it matches, it increments the value.

```<code>    for i, logLine in enumerate(logHandle):         #start matching UUID entries in log file to UUID from rulebase
        if logFunc.progress(lineCount, logSize):    #check progress
            print logFunc.progress(lineCount, logSize)  #print progress in 10% intervals
        for uid in uidHits:
            if logLine.count(uid) == 1:             #for each UUID, check the current line of the log for a match in the UUID list
                uidHits[uid] += 1                   #if matched, increment the relevant value in the uidHits list
                break                                #as we've already found the match, don't process the rest
        lineCount += 1
</code>```

It works as it should - but I'm sure there is a more efficient way of processing the file. I've been through a few guides and found that using 'count' is faster than using a compiled regex. I thought reading files in chunks rather than line by line would improve performance by reducing the amount of disk I/O time but the performance difference on a test file ~200MB was neglible. If anyone has any other methods I would be very grateful :)

答:
Try measuring where most time is spent, using a profiler http://docs.python.org/library/profile.html

Where best to optimise will depend on the nature of your data: If the list of uuids isn't very long, you may find, for example, that a large proportion of time is spend on the "if logFunc.progress(lineCount, logSize)". If the list is very long, you it could help to save the result of uidHits.keys() to a variable outside the loop and iterate over that instead of the dictionary itself, but Rosh Oxymoron's suggesting of finding the id first and then checking for it in uidHits would probably help even more.

In any case, you can eliminate the lineCount variable, and use i instead. And find(uid) != -1 might be better than count(uid) == 1 if the lines are very long.

ContentLicense: CC BY-SA 3.0

Body:
I'm working on a Python script to go through two files - one containing a list of UUIDs, the other containing a large amount of log entries - each line containing one of the UUIDs from the other file. The purpose of the program is to create a list of the UUIDS from file1, then for each time that UUID is found in the log file, increment the associated value for each time a match is found.

So long story short, count how many times each UUID appears in the log file.
At the moment, I have a list which is populated with UUID as the key, and 'hits' as the value. Then another loop which iterates over each line of the log file, and checking if the UUID in the log matches a UUID in the UUID list. If it matches, it increments the value.

    for i, logLine in enumerate(logHandle):         #start matching UUID entries in log file to UUID from rulebase
        if logFunc.progress(lineCount, logSize):    #check progress
            print logFunc.progress(lineCount, logSize)  #print progress in 10% intervals
        for uid in uidHits:
            if logLine.count(uid) == 1:             #for each UUID, check the current line of the log for a match in the UUID list
                uidHits[uid] += 1                   #if matched, increment the relevant value in the uidHits list
                break                                #as we've already found the match, don't process the rest
        lineCount += 1

It works as it should - but I'm sure there is a more efficient way of processing the file. I've been through a few guides and found that using 'count' is faster than using a compiled regex. I thought reading files in chunks rather than line by line would improve performance by reducing the amount of disk I/O time but the performance difference on a test file ~200MB was neglible. If anyone has any other methods I would be very grateful :)


问:
Trying to understand one-class SVM
I am trying to use one-class SVM with Python scikit-learn.
But I do not understand what are the different variables X_outliers, n_error_train, n_error_test, n_error_outliers, etc. which are at this address. Why does X is randomly selected and is not a part of a dataset?

Scikit-learn "documentation" did not help me a lot. Also, I found very few examples on Internet

Can I use One-class SVM for outlier detection in a case of a hudge number of data and if I do not know if there are anomalies in my training set?

One-class SVM is an Unsupervised Outlier Detection (here)

One-class SVM is not an outlier-detection method, but a
novelty-detection method (here)

Is this possible?

答: Many Sklearn examples are usually based on randomly generated data. If you want to see an example of how OneClassSVM works on a real dataset for outlier detection, you can go through my post: https://justanoderbit.com/outlier-detection/one-class-svm/</p>

Title: Trying to understand one-class SVM

ContentLicense: CC BY-SA 4.0


问:
org.postgresql.util.PSQLException: FATAL: database "pma-springbootdb"
I am working on my first sprinboot application, Where am trying to configure the properties for postgreSQL Database in my sprinboot application. When i run this application i am getting following error.

```<code>**org.postgresql.util.PSQLException: FATAL: database "pma-springbootdb" does not exist**
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2533) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.core.v3.QueryExecutorImpl.readStartupMessages(QueryExecutorImpl.java:2645) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.core.v3.QueryExecutorImpl.<init>(QueryExecutorImpl.java:138) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:255) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.jd
......
2020-06-03 09:33:13.052  WARN 1225 --- [         task-1] o.h.e.j.e.i.JdbcEnvironmentInitiator     : HHH000342: Could not obtain connection to query metadata : FATAL: database "pma-springbootdb" does not exist
2020-06-03 09:33:13.078  WARN 1225 --- [  restartedMain] ConfigServletWebServerApplicationContext : **Exception encountered during context initialization - cancelling refresh attempt: nested exception is org.springframework.beans.factory.BeanCreationException:** Error creating bean with name 'mvcConversionService' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is **org.springframework.beans.BeanInstantiationException: Failed to instantiate**
**Related cause: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'requestMappingHandlerAdapter'** defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Unsatisfied dependency expressed   : Invocation of destroy method failed on bean with name 'entityManagerFactory': org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
2020-06-03 09:33:13.079  INFO 1225 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
2020-06-03 09:33:13.084  INFO 1225 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2020-06-03 09:33:13.112  INFO 1225 --- [  restartedMain] ConditionEvaluationReportLoggingListener
**Caused by: org.springframework.beans.factory.BeanCreationException:** Error creating bean with name 'mvcConversionService' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.format.support.FormattingConversionService]: Factory method 'mvcConversionService' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepository' defined in com.jrp.pma.dao.EmployeeRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext'
</code>```

PostgreSQL properties

spring.datasource.url=jdbc:postgresql://localhost:5432/pma-springbootdb

```<code>spring.datasource.username=***

spring.datasource.password=***

spring.datasource.initialization-mode=never

spring.jpa.hibernate.ddl-auto=none

spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true

spring.jpa.show-sql=true
spring.thymeleaf.cache=false
version=3.0.0
</code>```

SQL Query

CREATE SEQUENCE IF NOT EXISTS employee_seq;

```<code>CREATE TABLE IF NOT EXISTS employee (

employee_id BIGINT NOT NULL DEFAULT nextval('employee_seq') PRIMARY KEY,
email VARCHAR(100) NOT NULL,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) NOT NULL

);

CREATE SEQUENCE IF NOT EXISTS project_seq;

CREATE TABLE IF NOT EXISTS project (

project_id BIGINT NOT NULL DEFAULT nextval('project_seq') PRIMARY KEY,
name VARCHAR(100) NOT NULL,
stage VARCHAR(100) NOT NULL,
description VARCHAR(500) NOT NULL

);

CREATE TABLE IF NOT EXISTS project_employee (

project_id BIGINT REFERENCES project,
employee_id BIGINT REFERENCES employee

);
</code>```

Project.java

```<code> @Entity
    public class Project {

@Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "project_seq")

private Long projectId;
    ....
    ....
     }
</code>```

*

Employee.java

*

```<code>@Entity
public class Employee {
@Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "employee_seq")
    private long employeeId;
...
..
}
</code>```

答:
The message database "pma-springbootdb" does not exist is self-explanatory.

This database does not exist in the PostgreSQL instance running on localhost with port 5432. Either it's a wrong database name or it's the wrong instance.

Please doublecheck: pma-springbootdb vs pma-springbootbd

Body:
I am working on my first sprinboot application, Where am trying to configure the properties for postgreSQL Database in my sprinboot application. When i run this application i am getting following error.

**org.postgresql.util.PSQLException: FATAL: database "pma-springbootdb" does not exist**
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2533) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.core.v3.QueryExecutorImpl.readStartupMessages(QueryExecutorImpl.java:2645) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.core.v3.QueryExecutorImpl.<init>(QueryExecutorImpl.java:138) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:255) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49) ~[postgresql-42.2.12.jar:42.2.12]
    at org.postgresql.jd
......
2020-06-03 09:33:13.052  WARN 1225 --- [         task-1] o.h.e.j.e.i.JdbcEnvironmentInitiator     : HHH000342: Could not obtain connection to query metadata : FATAL: database "pma-springbootdb" does not exist
2020-06-03 09:33:13.078  WARN 1225 --- [  restartedMain] ConfigServletWebServerApplicationContext : **Exception encountered during context initialization - cancelling refresh attempt: nested exception is org.springframework.beans.factory.BeanCreationException:** Error creating bean with name 'mvcConversionService' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is **org.springframework.beans.BeanInstantiationException: Failed to instantiate**
**Related cause: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'requestMappingHandlerAdapter'** defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Unsatisfied dependency expressed   : Invocation of destroy method failed on bean with name 'entityManagerFactory': org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
2020-06-03 09:33:13.079  INFO 1225 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
2020-06-03 09:33:13.084  INFO 1225 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2020-06-03 09:33:13.112  INFO 1225 --- [  restartedMain] ConditionEvaluationReportLoggingListener
**Caused by: org.springframework.beans.factory.BeanCreationException:** Error creating bean with name 'mvcConversionService' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.format.support.FormattingConversionService]: Factory method 'mvcConversionService' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepository' defined in com.jrp.pma.dao.EmployeeRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext'

PostgreSQL properties

spring.datasource.url=jdbc:postgresql://localhost:5432/pma-springbootdb

spring.datasource.username=***

spring.datasource.password=***

spring.datasource.initialization-mode=never

spring.jpa.hibernate.ddl-auto=none

spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true

spring.jpa.show-sql=true
spring.thymeleaf.cache=false
version=3.0.0

SQL Query

CREATE SEQUENCE IF NOT EXISTS employee_seq;

CREATE TABLE IF NOT EXISTS employee (

employee_id BIGINT NOT NULL DEFAULT nextval('employee_seq') PRIMARY KEY,
email VARCHAR(100) NOT NULL,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) NOT NULL

);

CREATE SEQUENCE IF NOT EXISTS project_seq;

CREATE TABLE IF NOT EXISTS project (

project_id BIGINT NOT NULL DEFAULT nextval('project_seq') PRIMARY KEY,
name VARCHAR(100) NOT NULL,
stage VARCHAR(100) NOT NULL,
description VARCHAR(500) NOT NULL

);

CREATE TABLE IF NOT EXISTS project_employee (

project_id BIGINT REFERENCES project,
employee_id BIGINT REFERENCES employee

);

Project.java

 @Entity
    public class Project {

@Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "project_seq")

private Long projectId;
    ....
    ....
     }

*

Employee.java

*

@Entity
public class Employee {
@Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "employee_seq")
    private long employeeId;
...
..
}


问:
ScrollView with Autolayout issue Xcode 11.X
I am using scrollView with autolayout in Xcode 11.5 and Swift 5, but i have some problems with the contentSize of the scrollView.The problem is that the contentView.bounds.size is returning bigger value than screen size. I want it to work on older versions of iOS like ios 10 so Content Layout and Frame Layout is not possible.

In Storyboard I have the next one:

UIView

---ScrollView (pinned leading, trailing, top and bottom to 0 to superview)

-------- ContentView (pinned leading, trailing, top and bottom to 0 to scrollView and equal Height and Width to UIView)

---------------- *UIImage, UIButton, UILabel, etc.

MyProject - testing scrollView (ios target 10.0)

MyProject - testing scrollView (ios target 10.0)

TesstProject - testing scrollView (ios target 13.0)

*Constraints are the same

Any help or suggestions, please?

答:
Decrease the priority of contentView's height constraint to 250 in Interface Builder. It should be breakable. And there is no reason to override viewDidLayoutSubviews you should remove this.

How to configure a UIScrollView with Auto Layout in Interface Builder.

You should set ContentView's height and width to Super View which is top of the hierarchy


问:
Too Many Files Open while monitoring file changes
I am developing a document-browser-based app for the iPad. I have been using SKQueue to monitor changes to the files in order to make sure their metadata remains current when the user performs actions in the document browser. The code for initiating monitoring:

```<code>    // Set up the queue
    let delegate = self
    queue = SKQueue(delegate: delegate)!
    // Remove all existing paths
    queue?.removeAllPaths()

    // Get the list of PDF URLs using a function that enumerates a folder's contents
    let pdfFiles = getFolderContents(rootFolder: myDocumentsFolder, extensionWanted: "pdf")
    for pdfFilePath in pdfFiles.filePaths {
        queue?.addPath(pdfFilePath.path)
    }
    for pdfFolderPath in pdfFiles.folderPaths {
        queue?.addPath(pdfFolderPath.path)
    }
</code>```

I developed my own logic to respond to notifications from this queue, but I do not remove any items from the queue during the app's runtime.

The problem - it seems that when the number of items watched is over 200 (files and folders) the system hits a wall and the console reports error 24: Too Many Files Open. After that, no reading/writing of any file can be performed.

From what I was able to gather from searching, it seems that iOS and iPadOS do not allow more than 256 files descriptors to be accessed at the same time, and that would mean that the GCD approach to monitoring file changes would suffer from the same limitation.

Is there any way to monitor files changes that is not subject to such a limitation? Any other suggestions?

答:
After a lot of research and experimentation, I can finally verify that indeed, the default maximum number allowed of open file descriptors is 256 - for MacOS, iOS and iPadOS. This can be changed easily in MacOS - see article here. However, iOS and iPadOS being much more closed in nature, there is no reliable way of changing this limit on these platforms.

Good practices are therefore:

Try to avoid designing an app that would call for so many file descriptors open.

Monitor directories, and not individual files. With most tools available for monitoring the file system, you get notifications for any file change within a monitored directory. Just implement your logic from there, by enumerating the folder and comparing its new state with a saved state. You can find good code for that in the top two answers of this SO thread.

Note: I recommend enumeration rather than other methods of getting the file system state, because other methods tend to give incompatible results between the simulator and actual devices (different treatment of symlink resolution).

Make sure your method of choice for monitoring the file system can be queried for the number of items being watched, and issue an alert if the user approaches a set limit. Remember that the 256 open files must also include all files used by the app, including ones in the app's bundle and ones that are in actual use. So take a nice safety margin.

In my case, my app uses a UIDocumentBrowserViewController, or in other words - Apple's own Files app, to allow users to manage their files. I have to keep my metadata up-to-date with the file system state, and I have no control over the file management habits of my users. To complicate matters, the Files app itself can be used to modify the app's file system - while my app is not active.

Therefore, I do two things:

I save a detailed state of the file system from the App Delegate's applicationDidEnterBackground and applicationWillTerminate methods into a json file in Application Support, and on the app's launch I compare it to a fresh enumeration of the file system - and alert the user for any mismatch, suggesting to use the app's own file browser next time.

I created my own swift package, named SFSMonitor, for monitoring the file system. It is based on the wonderfully convenient SKQueue (which I highly recommend), but instead of monitoring kevent, it uses Dispatch Sources - a more modern approach, which Apple advocates. It is similar to Apple's own Directory Monitor (reference to which you can find here), but instead of monitoring one directory, it allows you to create and manage a whole queue of them. This class allows you to set a maximum number of monitored file descriptors, and be notified when that limit is reached.

Body:
I am developing a document-browser-based app for the iPad. I have been using SKQueue to monitor changes to the files in order to make sure their metadata remains current when the user performs actions in the document browser. The code for initiating monitoring:

    // Set up the queue
    let delegate = self
    queue = SKQueue(delegate: delegate)!
    // Remove all existing paths
    queue?.removeAllPaths()

    // Get the list of PDF URLs using a function that enumerates a folder's contents
    let pdfFiles = getFolderContents(rootFolder: myDocumentsFolder, extensionWanted: "pdf")
    for pdfFilePath in pdfFiles.filePaths {
        queue?.addPath(pdfFilePath.path)
    }
    for pdfFolderPath in pdfFiles.folderPaths {
        queue?.addPath(pdfFolderPath.path)
    }

I developed my own logic to respond to notifications from this queue, but I do not remove any items from the queue during the app's runtime.

The problem - it seems that when the number of items watched is over 200 (files and folders) the system hits a wall and the console reports error 24: Too Many Files Open. After that, no reading/writing of any file can be performed.

From what I was able to gather from searching, it seems that iOS and iPadOS do not allow more than 256 files descriptors to be accessed at the same time, and that would mean that the GCD approach to monitoring file changes would suffer from the same limitation.

Is there any way to monitor files changes that is not subject to such a limitation? Any other suggestions?


问:
How many bits is a WORD and is that constant over different architectures?
Is a machine WORD always the same or does it depend on the machine architecture?
And is the meaning of the word WORD context sensitive or generally applicable?

答:
Yes.

Ok, let me be a bit clearer. Assuming we are talking about words of memory, there are two broad definitions.

First, a word is often the natural size of a single item that can be accessed atomically in the hardware. That is very much a platform dependent size, but is usually 16, 32, or 64 bits, but other sizes have been found in the wild.

Second, it is often used to specifically mean a 16-bit value. In that context, you will see DWORD used to mean a 32-bit value. This usage is common on x86 platforms, especially Windows, but was used on DEC PDP-11 and VAX, and Motorola 68000 descendants as well.

Telling which is the intended usage depends on context...

OwnerDisplayName: mixedpickles

OwnerDisplayName: RBerteig

ContentLicense: CC BY-SA 2.5


问:
Where is the Object class or java.lang imported into the scala package or Any class?
From my understanding the ultimate class in Scala is Any class. However, I thought Scala built of the Java, so would not the ultimate class be Object? I have been checking the documentation and I could be wrong but it does not show that Object is the parent class of Any nor can I see anywhere the java.lang package being imported into Scala, which should be its backbone right?

答:
You are confusing the Scala Programming Language with one of its Implementations.

A Programming Language is a set of mathematical rules and restrictions. Not more. It isn't "written in anything" (except maybe in English) and it isn't "built off anything" (except maybe the paper that the specification is written on).

An Implementation is a piece of software that either reads a program written in the Programming Language and executes that program in such a way that the exact things that the Programming Language Specification say should happen, do happen (in which case we call the Implementation an Interpreter), or it reads the program and outputs another program in another language in such a way that executing that output program with an interpreter for its language makes things happen in exactly the way that the Specification for the input language says.

Either way, it is the job of the person writing the Implementation to make sure that his Implementation does what the Specification says it should do.

So, even if I am writing an Implementation of Scala that is "built off Java" and written in Java, I still need to make sure that Any is the top type, because that's what the Scala Language Specification says. It is probably instructive to look at how, exactly, the Scala Language Specification phrases this [bold emphasis mine]:

Classes AnyRef and AnyVal are required to provide only the members declared in class Any, but implementations may add host-specific methods to these classes (for instance, an implementation may identify class AnyRef with its own root class for objects).

There are currently three actively-maintained Implementations of Scala, and one abandoned one.

The abandoned Implementation of Scala is Scala.NET, which was a compiler targeting the Common Language Infrastructure. It was abandoned due to lack of interest and funding. (Basically, all the users that probably would have used Scala.NET were already using F#.)

The currently maintained Implementations of Scala are:

Scala-native: a compiled Implementation targeting unixoid Operating Systems and Windows.

Scala.js: a compiled Implementation targeting the ECMAScript and Web platform.

Scala (a rather unfortunately confusing name, because it is the same as the language): a compiled Implementation targeting the Java platform. And by "Java platform", I mean the Java Virtual Machine and the Java Runtime Environment but not the Java Programming Language.

All three Implementations are written 100% in Scala. Actually, they are not three fully independent implementations, they use the same compiler frontend with only different backends, and they use the same parts of the Scala Standard Library that are written in Scala, and only re-implement the parts written in other languages.

So, what is true is that the Java Implementation of Scala does indeed do something with java.lang.Object. However, java.lang.Object is not the superclass of scala.Any. In fact, it can't be because scala.Any is the root superclass of both reference types and value types, whereas java.lang.Object is only the root superclass of all reference types. Therefore, java.lang.Object is actually equivalent to scala.AnyRef and not to scala.Any. However, java.lang.Object is not the superclass of scala.AnyRef either, but rather, both are the same class.

Also, java.lang._ is automatically imported just like scala._ is. But this does not apply to the Scala Programming Language, it only applies to the Java Implementation of the Scala Programming Language, whose name is unfortunately also Scala.

So, only for one of the three Implementations, there is some truth to the statement that java.lang.Object is the root class, but it is not a superclass of scala.Any, rather it is the same class as scala.AnyRef.

But again, this is only true for the Java Implementation of Scala. For example, in Scala.NET, the root superclass would be identified with System.Object, not java.lang.Object, and it would be equivalent to scala.Any, not scala.AnyRef because the CLI has a unified type system like Scala where reference types and value types are unified in the same type system. And I haven't checked Scala.js, but I would assume that it would identify Object with scala.AnyRef.

Note, however, that none of this is because the Implementation is "built off" something. The reason for doing this, for trying to merge the Scala and Java / CLI / ECMAScript class hierarchy, is for interoperability, it is for making it easy to call Scala code from every other language on the Java / CLI / ECMAScript platform, and vice versa, call code written in other languages from Scala. If you didn't care about that, then there would be no need to jump through these hoops.


问:
Skip JWT Auth during Tests ASP.Net Core 3.1 Web Api
I a have a very simple app with one JWT authenticated controller:

[ApiController]
[Authorize]
[Route("[controller]")]
public class JwtController : ControllerBase
{

    public JwtController() { }

    [HttpGet]
    public ActionResult Get() => Ok("Working!");
}
```

<p>With the authentication configured as:</p>

<pre class="lang-cs prettyprint-override"><code>services.AddAuthentication(x =>
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
    x.RequireHttpsMetadata = false;
    x.SaveToken = true;
    x.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = false,
        ValidateAudience = false
    };
});
</code>```

During tests, i want the user to be "authenticated" all the time so that [Authorize] would be skipped.

[Fact]
public async Task JwtIsSkipped()
{
    var response = (await _Client.GetAsync("/jwt")).EnsureSuccessStatusCode();
    var stringResponse = await response.Content.ReadAsStringAsync();

    Assert.Equal("Working!", stringResponse);
}
```

<p>Running the test like this will fail, so following this doc I added this simple auth handler:</p>

<pre class="lang-cs prettyprint-override"><code>public class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    public const string DefaultScheme = "Test";
    public TestAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
        ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
        : base(options, logger, encoder, clock)
    {
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var claims = new[] { new Claim(ClaimTypes.Name, "Test user") };
        var identity = new ClaimsIdentity(claims, DefaultScheme);
        var principal = new ClaimsPrincipal(identity);
        var ticket = new AuthenticationTicket(principal, DefaultScheme);

        return Task.FromResult(AuthenticateResult.Success(ticket));
    }
}
</code>```

So now my test class looks like this:

public class UnitTest : IClassFixture<WebApplicationFactory<Startup>>
{
    private readonly WebApplicationFactory<Startup> _Factory;
    private readonly HttpClient _Client;

    public UnitTest(WebApplicationFactory<Startup> factory)
    {
        _Factory = factory;
        _Client = _Factory.WithWebHostBuilder(builder =>
        {
            builder.ConfigureTestServices(services =>
            {
                services.AddAuthentication(TestAuthHandler.DefaultScheme)
                        .AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(
                            TestAuthHandler.DefaultScheme, options => { });
            });
        }).CreateClient();

        _Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(TestAuthHandler.DefaultScheme);
    }

    [Fact]
    public async Task JwtIsSkipped()
    {
        var response = (await _Client.GetAsync("/jwt")).EnsureSuccessStatusCode();
        var stringResponse = await response.Content.ReadAsStringAsync();

        Assert.Equal("Working!", stringResponse);
    }
}
```

And it still fails, I have no idea what I'm doing wrong.

答:
I have had a similar situation previously with the Microsoft example and can promise you it can give headaches, it may work on specific Core versions, but I have given up. I have solved this way.

My goal was, is to Authorize the system while testing, instead of using AddAuthentication in our test we create a FakePolicyEvaluator class and add it as a singleton to our test.

So let's go to our FakePolicyEvaluator class:

```<code>public class FakePolicyEvaluator : IPolicyEvaluator
{
    public virtual async Task<AuthenticateResult> AuthenticateAsync(AuthorizationPolicy policy, HttpContext context)
    {
        var principal = new ClaimsPrincipal();
        principal.AddIdentity(new ClaimsIdentity(new[] {
            new Claim("Permission", "CanViewPage"),
            new Claim("Manager", "yes"),
            new Claim(ClaimTypes.Role, "Administrator"),
            new Claim(ClaimTypes.NameIdentifier, "John")
        }, "FakeScheme"));
        return await Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal,
            new AuthenticationProperties(), "FakeScheme")));
    }

    public virtual async Task<PolicyAuthorizationResult> AuthorizeAsync(AuthorizationPolicy policy,
        AuthenticateResult authenticationResult, HttpContext context, object resource)
    {
        return await Task.FromResult(PolicyAuthorizationResult.Success());
    }
}
</code>```

Then in our ConfigureTestServices we added services.AddSingleton<IPolicyEvaluator, FakePolicyEvaluator>();

So in your test code like this:

```<code>private readonly HttpClient _client;

public UnitTest(WebApplicationFactory<Startup> factory)
{
    _client = factory.WithWebHostBuilder(builder =>
    {
        builder.ConfigureTestServices(services =>
        {
            services.AddSingleton<IPolicyEvaluator, FakePolicyEvaluator>();
        });
    }).CreateClient();
}

[Fact]
public async Task JwtIsSkipped()
{
    var response = (await _client.GetAsync("/jwt")).EnsureSuccessStatusCode();
    var stringResponse = await response.Content.ReadAsStringAsync();

    Assert.Equal("Working!", stringResponse);
}
</code>```

That is it. Now when you test, it will bypass authentication. I have tested it with the provided controller and it works.

It is also possible to place the fake inside the application startup, and it will be both testable for test and working under a development environment. Check the referenced article.

Disclaimer: I have written in more depth article about this on my personal website Reference where you can find and download a source code from GitHub.

Body:
I a have a very simple app with one JWT authenticated controller:

[ApiController]
[Authorize]
[Route("[controller]")]
public class JwtController : ControllerBase
{

    public JwtController() { }

    [HttpGet]
    public ActionResult Get() => Ok("Working!");
}

With the authentication configured as:

services.AddAuthentication(x =>
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
    x.RequireHttpsMetadata = false;
    x.SaveToken = true;
    x.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = false,
        ValidateAudience = false
    };
});

During tests, i want the user to be "authenticated" all the time so that [Authorize] would be skipped.

[Fact]
public async Task JwtIsSkipped()
{
    var response = (await _Client.GetAsync("/jwt")).EnsureSuccessStatusCode();
    var stringResponse = await response.Content.ReadAsStringAsync();

    Assert.Equal("Working!", stringResponse);
}

Running the test like this will fail, so following this doc I added this simple auth handler:

public class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    public const string DefaultScheme = "Test";
    public TestAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
        ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
        : base(options, logger, encoder, clock)
    {
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var claims = new[] { new Claim(ClaimTypes.Name, "Test user") };
        var identity = new ClaimsIdentity(claims, DefaultScheme);
        var principal = new ClaimsPrincipal(identity);
        var ticket = new AuthenticationTicket(principal, DefaultScheme);

        return Task.FromResult(AuthenticateResult.Success(ticket));
    }
}

So now my test class looks like this:

public class UnitTest : IClassFixture<WebApplicationFactory<Startup>>
{
    private readonly WebApplicationFactory<Startup> _Factory;
    private readonly HttpClient _Client;

    public UnitTest(WebApplicationFactory<Startup> factory)
    {
        _Factory = factory;
        _Client = _Factory.WithWebHostBuilder(builder =>
        {
            builder.ConfigureTestServices(services =>
            {
                services.AddAuthentication(TestAuthHandler.DefaultScheme)
                        .AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(
                            TestAuthHandler.DefaultScheme, options => { });
            });
        }).CreateClient();

        _Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(TestAuthHandler.DefaultScheme);
    }

    [Fact]
    public async Task JwtIsSkipped()
    {
        var response = (await _Client.GetAsync("/jwt")).EnsureSuccessStatusCode();
        var stringResponse = await response.Content.ReadAsStringAsync();

        Assert.Equal("Working!", stringResponse);
    }
}

And it still fails, I have no idea what I'm doing wrong.

Body:
I have had a similar situation previously with the Microsoft example and can promise you it can give headaches, it may work on specific Core versions, but I have given up. I have solved this way.

My goal was, is to Authorize the system while testing, instead of using AddAuthentication in our test we create a FakePolicyEvaluator class and add it as a singleton to our test.

So let's go to our FakePolicyEvaluator class:

public class FakePolicyEvaluator : IPolicyEvaluator
{
    public virtual async Task<AuthenticateResult> AuthenticateAsync(AuthorizationPolicy policy, HttpContext context)
    {
        var principal = new ClaimsPrincipal();
        principal.AddIdentity(new ClaimsIdentity(new[] {
            new Claim("Permission", "CanViewPage"),
            new Claim("Manager", "yes"),
            new Claim(ClaimTypes.Role, "Administrator"),
            new Claim(ClaimTypes.NameIdentifier, "John")
        }, "FakeScheme"));
        return await Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal,
            new AuthenticationProperties(), "FakeScheme")));
    }

    public virtual async Task<PolicyAuthorizationResult> AuthorizeAsync(AuthorizationPolicy policy,
        AuthenticateResult authenticationResult, HttpContext context, object resource)
    {
        return await Task.FromResult(PolicyAuthorizationResult.Success());
    }
}

Then in our ConfigureTestServices we added services.AddSingleton<IPolicyEvaluator, FakePolicyEvaluator>();

So in your test code like this:

private readonly HttpClient _client;

public UnitTest(WebApplicationFactory<Startup> factory)
{
    _client = factory.WithWebHostBuilder(builder =>
    {
        builder.ConfigureTestServices(services =>
        {
            services.AddSingleton<IPolicyEvaluator, FakePolicyEvaluator>();
        });
    }).CreateClient();
}

[Fact]
public async Task JwtIsSkipped()
{
    var response = (await _client.GetAsync("/jwt")).EnsureSuccessStatusCode();
    var stringResponse = await response.Content.ReadAsStringAsync();

    Assert.Equal("Working!", stringResponse);
}

That is it. Now when you test, it will bypass authentication. I have tested it with the provided controller and it works.

It is also possible to place the fake inside the application startup, and it will be both testable for test and working under a development environment. Check the referenced article.

Disclaimer: I have written in more depth article about this on my personal website Reference where you can find and download a source code from GitHub.


问:
applicationWillEnterForeground never called
Hey there, I'm trying Multitasking in the Simulator (I only have a 2nd gen iPod and an iPad) and I'm still having some problems. My testing methods look like this:

```<code>- (void)applicationDidBecomeActive:(UIApplication *)application {
 NSLog(@"Entering %s",__FUNCTION__);

 if (enteredFromBackground) {
  NSLog(@"Entering from Background");
  enteredFromBackground = NO;
 }
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
 NSLog(@"Entering %s",__FUNCTION__);

 enteredFromBackground = YES;
}
</code>```

Unforntunately, I'm not seeing the NSLog from applicationWillEnterForeground, that's why I added the line to show me something in applicationDidBecomeActive.
All I get is the

```<code>2010-11-20 15:58:12.796 iBeat[45997:207] Entering -[AppDelegate_Shared applicationDidEnterBackground:]
2010-11-20 15:58:18.160 iBeat[45997:207] Entering -[AppDelegate_Shared applicationDidBecomeActive:]
</code>```

答:
After having this problem in iOS 13, I found out that I was waiting for applicationWillEnterForeground(_ application: UIApplication) to be called instead of sceneWillEnterForeground(_ scene: UIScene).

For more information, read this answer:

enter link description here

Body:
Hey there, I'm trying Multitasking in the Simulator (I only have a 2nd gen iPod and an iPad) and I'm still having some problems. My testing methods look like this:

- (void)applicationDidBecomeActive:(UIApplication *)application {
 NSLog(@"Entering %s",__FUNCTION__);

 if (enteredFromBackground) {
  NSLog(@"Entering from Background");
  enteredFromBackground = NO;
 }
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
 NSLog(@"Entering %s",__FUNCTION__);

 enteredFromBackground = YES;
}

Unforntunately, I'm not seeing the NSLog from applicationWillEnterForeground, that's why I added the line to show me something in applicationDidBecomeActive.
All I get is the

2010-11-20 15:58:12.796 iBeat[45997:207] Entering -[AppDelegate_Shared applicationDidEnterBackground:]
2010-11-20 15:58:18.160 iBeat[45997:207] Entering -[AppDelegate_Shared applicationDidBecomeActive:]


问:
Autofac assembly scanning - .NET Core
I've been trying to get assembly scanning working in my .NET core 2.0 project.

The exception I am getting

```<code>Autofac.Core.Registration.ComponentNotRegisteredException
  HResult=0x80131500
  Message=The requested service 'Microsoft.AspNetCore.Hosting.Internal.WebHostOptions' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.
  Source=Autofac
  StackTrace:
   at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.AspNetCore.Hosting.WebHostExtensions.<RunAsync>d__4.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Hosting.WebHostExtensions.Run(IWebHost host)
   at Track4Corp.VehicleDatabase.Server.Program.Main(String[] args) in C:\Users\Admin\source\repos\VehicleDatabase-server\src\Track4Corp.VehicleDatabase.Server\Program.cs:line 10
</code>```

Program.cs

```<code>using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace Track4Corp.VehicleDatabase.Server
{
  public class Program
  {
    public static void Main(string[] args)
    {
      CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
  }
}
</code>```

Startup class

```<code>public class Startup
  {
    public Autofac.IContainer ApplicationContainer { get; private set; }

    public IConfigurationRoot Configuration { get; private set; }

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
//TODO: Move out of code before release
      services.AddDbContext<UserDBContext>(options => options.UseSqlServer("Server=DESKTOP-9L9IGFE;Database=DB;Trusted_Connection=True;"));

      //Autofac Assembly Registration
      ApplicationContainer = AutoFacAssemblyRegistration.RegisterAllAssemblies();

      return new AutofacServiceProvider(ApplicationContainer);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
      }

      app.Run(async (context) =>
      {
       await context.Response.WriteAsync("Hello World!");
      });
</code>```

So my actually builder i moved to another project, where I for now scan on a hardcorded path where I know all my dll files are located. I ran it in debug mode and see all of them being there.

```<code>  public class AutoFacAssemblyRegistration
  {
    public static IContainer RegisterAllAssemblies()
    {
      var builder = new ContainerBuilder();
      string executingDirectory = Directory.GetCurrentDirectory();
      // string[] files = Directory.GetFiles(executingDirectory, "*.dll");
      string[] files = Directory.GetFiles(@"PATH_HERE", "*.dll");

      var listOfAssemblies = new List<Assembly>();
      foreach (string item in files)
      {
        listOfAssemblies.Add(item: Assembly.LoadFile(item));
      }
      builder.RegisterAssemblyTypes(listOfAssemblies.ToArray()).AsImplementedInterfaces().InstancePerLifetimeScope();
      //builder.RegisterAssemblyModules(listOfAssemblies.ToArray());

      return builder.Build();
    }
  }
</code>```

I also tried different sort of solutions to register the assemblies, such as

```<code>foreach (Assembly item in listOfAssemblies)
{
  System.Type[] assemblyType = item.GetTypes();
  foreach (System.Type typeItem in assemblyType)
  {
    if (typeItem.IsInterface)
    {
      Autofac.Builder.IRegistrationBuilder<object, Autofac.Builder.ConcreteReflectionActivatorData,
        Autofac.Builder.SingleRegistrationStyle> registration =
        builder.RegisterType(typeItem).AsImplementedInterfaces();

      if (typeItem.GetInterfaces().Any(i => i.IsAssignableFrom(typeof(ISingletonDependency))))
      {
        registration.SingleInstance();
      }
      else
      {
        registration.InstancePerRequest();
      }
    }
  }
}
</code>```

I am wondering if I am doing something wrong, or perhaps this is not possible in .NET core 2.1 projects?

Would be nice if anyone could hint me in the right direction, how to solve my problem.

答:
Had a similar issue and solved it by adding containerBuilder.Populate(serviceCollection) before doing containerBuilder.Build().

Following the sample you provided in your question, it would look something like this -

```<code>  public class AutoFacAssemblyRegistration
  {
    public static IContainer RegisterAllAssemblies(IServiceCollection services)
    {
      var builder = new ContainerBuilder();
      builder.Populate(services);
      string executingDirectory = Directory.GetCurrentDirectory();
      // string[] files = Directory.GetFiles(executingDirectory, "*.dll");
      string[] files = Directory.GetFiles(@"PATH_HERE", "*.dll");

      var listOfAssemblies = new List<Assembly>();
      foreach (string item in files)
      {
        listOfAssemblies.Add(item: Assembly.LoadFile(item));
      }
      builder.RegisterAssemblyTypes(listOfAssemblies.ToArray()).AsImplementedInterfaces().InstancePerLifetimeScope();
      //builder.RegisterAssemblyModules(listOfAssemblies.ToArray());

      return builder.Build();
    }
  }
</code>```

Title: Autofac assembly scanning - .NET Core

Body:
I've been trying to get assembly scanning working in my .NET core 2.0 project.

The exception I am getting

Autofac.Core.Registration.ComponentNotRegisteredException
  HResult=0x80131500
  Message=The requested service 'Microsoft.AspNetCore.Hosting.Internal.WebHostOptions' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.
  Source=Autofac
  StackTrace:
   at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.AspNetCore.Hosting.WebHostExtensions.<RunAsync>d__4.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Hosting.WebHostExtensions.Run(IWebHost host)
   at Track4Corp.VehicleDatabase.Server.Program.Main(String[] args) in C:\Users\Admin\source\repos\VehicleDatabase-server\src\Track4Corp.VehicleDatabase.Server\Program.cs:line 10

Program.cs

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace Track4Corp.VehicleDatabase.Server
{
  public class Program
  {
    public static void Main(string[] args)
    {
      CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
  }
}

Startup class

public class Startup
  {
    public Autofac.IContainer ApplicationContainer { get; private set; }

    public IConfigurationRoot Configuration { get; private set; }

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
//TODO: Move out of code before release
      services.AddDbContext<UserDBContext>(options => options.UseSqlServer("Server=DESKTOP-9L9IGFE;Database=DB;Trusted_Connection=True;"));

      //Autofac Assembly Registration
      ApplicationContainer = AutoFacAssemblyRegistration.RegisterAllAssemblies();

      return new AutofacServiceProvider(ApplicationContainer);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
      }

      app.Run(async (context) =>
      {
       await context.Response.WriteAsync("Hello World!");
      });

So my actually builder i moved to another project, where I for now scan on a hardcorded path where I know all my dll files are located. I ran it in debug mode and see all of them being there.

  public class AutoFacAssemblyRegistration
  {
    public static IContainer RegisterAllAssemblies()
    {
      var builder = new ContainerBuilder();
      string executingDirectory = Directory.GetCurrentDirectory();
      // string[] files = Directory.GetFiles(executingDirectory, "*.dll");
      string[] files = Directory.GetFiles(@"PATH_HERE", "*.dll");

      var listOfAssemblies = new List<Assembly>();
      foreach (string item in files)
      {
        listOfAssemblies.Add(item: Assembly.LoadFile(item));
      }
      builder.RegisterAssemblyTypes(listOfAssemblies.ToArray()).AsImplementedInterfaces().InstancePerLifetimeScope();
      //builder.RegisterAssemblyModules(listOfAssemblies.ToArray());

      return builder.Build();
    }
  }

I also tried different sort of solutions to register the assemblies, such as

foreach (Assembly item in listOfAssemblies)
{
  System.Type[] assemblyType = item.GetTypes();
  foreach (System.Type typeItem in assemblyType)
  {
    if (typeItem.IsInterface)
    {
      Autofac.Builder.IRegistrationBuilder<object, Autofac.Builder.ConcreteReflectionActivatorData,
        Autofac.Builder.SingleRegistrationStyle> registration =
        builder.RegisterType(typeItem).AsImplementedInterfaces();

      if (typeItem.GetInterfaces().Any(i => i.IsAssignableFrom(typeof(ISingletonDependency))))
      {
        registration.SingleInstance();
      }
      else
      {
        registration.InstancePerRequest();
      }
    }
  }
}

I am wondering if I am doing something wrong, or perhaps this is not possible in .NET core 2.1 projects?

Would be nice if anyone could hint me in the right direction, how to solve my problem.

Body:
Had a similar issue and solved it by adding containerBuilder.Populate(serviceCollection) before doing containerBuilder.Build().

Following the sample you provided in your question, it would look something like this -

  public class AutoFacAssemblyRegistration
  {
    public static IContainer RegisterAllAssemblies(IServiceCollection services)
    {
      var builder = new ContainerBuilder();
      builder.Populate(services);
      string executingDirectory = Directory.GetCurrentDirectory();
      // string[] files = Directory.GetFiles(executingDirectory, "*.dll");
      string[] files = Directory.GetFiles(@"PATH_HERE", "*.dll");

      var listOfAssemblies = new List<Assembly>();
      foreach (string item in files)
      {
        listOfAssemblies.Add(item: Assembly.LoadFile(item));
      }
      builder.RegisterAssemblyTypes(listOfAssemblies.ToArray()).AsImplementedInterfaces().InstancePerLifetimeScope();
      //builder.RegisterAssemblyModules(listOfAssemblies.ToArray());

      return builder.Build();
    }
  }


问:
Query param not behaving as expected
I'm using an :order query param to pass an order argument to my function. Unfortunately, it seems not to have an effect on the output.

The request debugging output shows the order argument is parsed correctly:

Parameter #2(cf_sql_varchar) = posts.createdAt ASC

Yet it still makes no difference to output. If I hard code the argument (ORDER BY ..., #arguments.order#), it works fine.

Any ideas?

```<code>public any function getPost(required numeric postId, string order)
{
    switch(arguments.order)
    {
        case "new":
            arguments.order = "posts.createdAt DESC";
            break;
        case "old":
            arguments.order = "posts.createdAt ASC";
            break;
        default:
            arguments.order = "posts.score DESC";
    }

    local.post = new Query(dataSource=variables.wheels.class.connection.datasource);
    local.post.setSql("
        SELECT *
        FROM
        WHERE posts.id = :postId OR posts.parentId = :postId
        ORDER BY posts.postTypeId ASC, :order"
    );

    local.post.addParam(name="postId", cfsqltype="cf_sql_integer", value=arguments.postId, maxlength=10);
    local.post.addParam(name="order", cfsqltype="cf_sql_varchar", value=arguments.order, maxlength=20);
    local.post = local.post.execute().getResult();

    return local.post;
</code>```

}

答: If I remember correctly, queryparams won't work anywhere except in the where clause. So you're not dealing with a bug, but a limitation.</p>

Title: Query param not behaving as expected

Body:
I'm using an :order query param to pass an order argument to my function. Unfortunately, it seems not to have an effect on the output.

The request debugging output shows the order argument is parsed correctly:

Parameter #2(cf_sql_varchar) = posts.createdAt ASC

Yet it still makes no difference to output. If I hard code the argument (ORDER BY ..., #arguments.order#), it works fine.

Any ideas?

public any function getPost(required numeric postId, string order)
{
    switch(arguments.order)
    {
        case "new":
            arguments.order = "posts.createdAt DESC";
            break;
        case "old":
            arguments.order = "posts.createdAt ASC";
            break;
        default:
            arguments.order = "posts.score DESC";
    }

    local.post = new Query(dataSource=variables.wheels.class.connection.datasource);
    local.post.setSql("
        SELECT *
        FROM
        WHERE posts.id = :postId OR posts.parentId = :postId
        ORDER BY posts.postTypeId ASC, :order"
    );

    local.post.addParam(name="postId", cfsqltype="cf_sql_integer", value=arguments.postId, maxlength=10);
    local.post.addParam(name="order", cfsqltype="cf_sql_varchar", value=arguments.order, maxlength=20);
    local.post = local.post.execute().getResult();

    return local.post;

}


问:
Focus in a field of subform from main form
I have a button in the main form which adds a value to the sub-form. I want to then set focus on the "quantity" field in the added record in the subform, but following the other questions and instructions I found online does not seem to work. If you could fill me in why the following code does not work that would be great!</p>

```<code>Private Sub insertAtPrice(price)
    DoCmd.RunCommand acCmdSaveRecord
    DoCmd.SetWarnings False
    Dim SQl As String
    ' Invoice Code Item Retail Quant Wholesale Total
    SQl = "INSERT INTO ORDERLINE ( Invoice, Code, Item, Cost, Quant, Price) VALUES ('" & Me.Invoice.value & "', '000Y1', 'Fruit/Veg', " & price & ".00\2, 1, " & price & ".00)"
    DoCmd.RunSQL SQl
    DoCmd.SetWarnings True
    Me.AINVOICELINE_subform.Requery
    'Focus into quantity of new record
    With Me.AINVOICELINE_subform.Form.RecordsetClone
        .FindFirst "Key = " & DMax("[Key]", "ORDERLINE")
        If .NoMatch Then 'just in case another user deleted it in the interim
          MsgBox "Record not found!", vbCritical
        Else 'go to that record
          Me.AINVOICELINE_subform.Form.Bookmark = .Bookmark
        End If
    End With
End Sub
</code>```

答:
How do you set the focus in the field? After inserting the new record you have to call

```<code>Me.AINVOICELINE_subform.Form!quantity.SetFocus
</code>```

Alternatively you can edit the tab order of your form controls so that the quantity field gets the focus first and disable the TabStop property for fields you to not need to be focusable.

Body:
I have a button in the main form which adds a value to the sub-form. I want to then set focus on the "quantity" field in the added record in the subform, but following the other questions and instructions I found online does not seem to work. If you could fill me in why the following code does not work that would be great!

Private Sub insertAtPrice(price)
    DoCmd.RunCommand acCmdSaveRecord
    DoCmd.SetWarnings False
    Dim SQl As String
    ' Invoice Code Item Retail Quant Wholesale Total
    SQl = "INSERT INTO ORDERLINE ( Invoice, Code, Item, Cost, Quant, Price) VALUES ('" & Me.Invoice.value & "', '000Y1', 'Fruit/Veg', " & price & ".00\2, 1, " & price & ".00)"
    DoCmd.RunSQL SQl
    DoCmd.SetWarnings True
    Me.AINVOICELINE_subform.Requery
    'Focus into quantity of new record
    With Me.AINVOICELINE_subform.Form.RecordsetClone
        .FindFirst "Key = " & DMax("[Key]", "ORDERLINE")
        If .NoMatch Then 'just in case another user deleted it in the interim
          MsgBox "Record not found!", vbCritical
        Else 'go to that record
          Me.AINVOICELINE_subform.Form.Bookmark = .Bookmark
        End If
    End With
End Sub

Body:
How do you set the focus in the field? After inserting the new record you have to call

Me.AINVOICELINE_subform.Form!quantity.SetFocus

Alternatively you can edit the tab order of your form controls so that the quantity field gets the focus first and disable the TabStop property for fields you to not need to be focusable.


问:
NodeJS with DynamoDB throws error "AttributeValue may not contain an empty string"
I had a problem with the fact that DynamoDB cannot accept empty strings as value in attributes.
I always had to check in the front end if there is an empty string value otherwise the API call would fail due to the error "An AttributeValue may not contain an empty string" that Dynamo DB would throw.

I was wandering if there is a recursive function that would remove the attributes that are not valid according to DynamoDB in order for the putItem or update request in DynamoDB to work.

答:
June 2020 Update:

DynamoDB now supports empty string values for non-key attributes: https://aws.amazon.com/about-aws/whats-new/2020/05/amazon-dynamodb-now-supports-empty-values-for-non-key-string-and-binary-attributes-in-dynamodb-tables/

In order to have consistent behavior, make sure that the client does not have { convertEmptyValues: true }, or else these attributes will be saved as NULL as opposed to an empty String.


问:
Efficiently batching Spark dataframes to call an API
I am fairly new to Spark and I'm trying to call the Spotify API using Spotipy. I have a list of artist ids which can be used to fetch artist info. The Spotify API allows for batch calls up to 50 ids at once. I load the artist ids from a MySQL database and store them in a dataframe.

My problem now is that I do not know how to efficiently batch that dataframe into pieces of 50 or less rows.

In the example below I'm turning the dataframe into a regular Python list from which I can call the API on batches of 50.

Any ideas how I could do this without going back to a Python list?

```<code>import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
from pyspark.sql import SparkSession
import os

spark = SparkSession\
        .builder\
        .appName("GetArtists")\
        .getOrCreate()

df = spark.read.format('jdbc') \
    .option("url", "jdbc:mysql://"+os.getenv("DB_SERVER")+":"+os.getenv("DB_PORT")+"/spotify_metadata")\
    .option("user", os.getenv("DB_USER"))\
    .option("password", os.getenv("DB_PW"))\
    .option("query", "SELECT artist_id FROM artists")\
    .load()

sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())

ids = [row['artist_id'] for row in df.collect()]

batch_size = 50
for i in range(0,len(ids), batch_size):
    artists = sp.artists( ids[i:i+batch_size] )

    # process the JSON response
</code>```

I thought about using foreach and calling the API for each id, but this results in unnecessary requests. Also the results are stored back in the database, which means that I am writing many single rows to the database.

答:
If you want to divide the dataframe based on the row number then you can do it like:

```<code>from pyspark.sql import functions as f
from pyspark.sql import Window

df = df.withColumn('row_num', f.row_number().over(Window.orderBy(f.lit(1))))
len = df.count()

for i in range(0,len, 50):
    df = df.filter(f.col('row_num')>=i & f.col('row_num')<=i+50)
    #api logic goes here
</code>```

But if you can pass the df to the api directly then pass df or collect df which will have only 50 values each time.

Body:
I am fairly new to Spark and I'm trying to call the Spotify API using Spotipy. I have a list of artist ids which can be used to fetch artist info. The Spotify API allows for batch calls up to 50 ids at once. I load the artist ids from a MySQL database and store them in a dataframe.

My problem now is that I do not know how to efficiently batch that dataframe into pieces of 50 or less rows.

In the example below I'm turning the dataframe into a regular Python list from which I can call the API on batches of 50.

Any ideas how I could do this without going back to a Python list?

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
from pyspark.sql import SparkSession
import os

spark = SparkSession\
        .builder\
        .appName("GetArtists")\
        .getOrCreate()

df = spark.read.format('jdbc') \
    .option("url", "jdbc:mysql://"+os.getenv("DB_SERVER")+":"+os.getenv("DB_PORT")+"/spotify_metadata")\
    .option("user", os.getenv("DB_USER"))\
    .option("password", os.getenv("DB_PW"))\
    .option("query", "SELECT artist_id FROM artists")\
    .load()

sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())

ids = [row['artist_id'] for row in df.collect()]

batch_size = 50
for i in range(0,len(ids), batch_size):
    artists = sp.artists( ids[i:i+batch_size] )

    # process the JSON response

I thought about using foreach and calling the API for each id, but this results in unnecessary requests. Also the results are stored back in the database, which means that I am writing many single rows to the database.

Body:
If you want to divide the dataframe based on the row number then you can do it like:

from pyspark.sql import functions as f
from pyspark.sql import Window

df = df.withColumn('row_num', f.row_number().over(Window.orderBy(f.lit(1))))
len = df.count()

for i in range(0,len, 50):
    df = df.filter(f.col('row_num')>=i & f.col('row_num')<=i+50)
    #api logic goes here

But if you can pass the df to the api directly then pass df or collect df which will have only 50 values each time.


问:
HTML5 - Select multi required-checkbox
I've writen some code here: http://jsfiddle.net/anhtran/kXsj9/8/

Users have to select at least 1 option on the group. But it makes me must click all of them to submit the form. How to do this issue without javascript?

Thanks for any help :)

答:
I think this html5 attribute is only supposed to define which fields are required.
You cant put logic in to say "at least one is required".

You will need to add custom javascript for this to work (and/or have validation on the server side).

hope this helps...

Title: HTML5 - Select multi required-checkbox


问:
Meaning of the done() function
Let us suppose you have the following action

```<code>export const startAddExpense = (expenseData = {}) => {
  return (dispatch) => {
    const {
      description = '',
      note = '',
      amount = 0,
      createdAt = 0
    } = expenseData;
    const expense = { description, note, amount, createdAt };

    return database.ref('expenses').push(expense).then((ref) => {
      dispatch(addExpense({
        id: ref.key,
        ...expense
      }));
    });
  };
};
</code>```

I am storing expenses data to a database(firebase in my case) and then I dispatch the addExpense function to the store

And here the test for it.

```<code>test('should add expense to database and store', (done) => {
    const store = createMockStore({});
    const expenseData = {
      description: 'Mouse',
      amount: 3000,
      note: 'This one is better',
      createdAt: 1000
    };

    store.dispatch(startAddExpense(expenseData)).then(() => {
      expect(1).toBe(1);
      done();
    });
});
</code>```

What is the meaning of the done() function? Does it mean the callback function should wait until the insertion of data in the firebase database has been completed?

Thanks,
Theo.

答:
done mean that your test function has asynchronous code. So you should manually call done when you get an async result. Also, async tests have third parameters that define timeout after that function would be considered as failed.
https://jasmine.github.io/tutorials/async#callbacks

Title: Meaning of the done() function

Body:
Let us suppose you have the following action

export const startAddExpense = (expenseData = {}) => {
  return (dispatch) => {
    const {
      description = '',
      note = '',
      amount = 0,
      createdAt = 0
    } = expenseData;
    const expense = { description, note, amount, createdAt };

    return database.ref('expenses').push(expense).then((ref) => {
      dispatch(addExpense({
        id: ref.key,
        ...expense
      }));
    });
  };
};

I am storing expenses data to a database(firebase in my case) and then I dispatch the addExpense function to the store

And here the test for it.

test('should add expense to database and store', (done) => {
    const store = createMockStore({});
    const expenseData = {
      description: 'Mouse',
      amount: 3000,
      note: 'This one is better',
      createdAt: 1000
    };

    store.dispatch(startAddExpense(expenseData)).then(() => {
      expect(1).toBe(1);
      done();
    });
});

What is the meaning of the done() function? Does it mean the callback function should wait until the insertion of data in the firebase database has been completed?

Thanks,
Theo.


问:
dhcpd[]: send_packet6: Bad file descriptor
I have a dhcpv6 server configured on ubuntu. i has static bindings defined for each client based on interface ID.
But when a client solicits, the allocation fails on the DHCPv6 server.
"dhcpd[122762]: send_packet6: Bad file descriptor"

----Config on dhcpv6 server----

```<code>subnet6 2404:e801:1014::/48 {
    host client-name-2404.e801.1014.5 {
        host-identifier option dhcp6.interface-id "OLT3923.IOT xpon 0/2/0/1:2404:e801:1014::5";
        fixed-address6 2404:e801:1014::5;
        fixed-prefix6 b1a1:3003:1014:5::/64;
    }
</code>```

----syslog message----

```<code>dhcpd[122762]: Relay-forward message from 2406:3003:1:5a::1 port 547, link address 2404:e801:1014::1, peer address fe80::244:1ff:fe00:1
dhcpd[122762]: Advertise NA: address 2404:e801:1014::5 to client with duid 00:01:00:01:26:69:f0:4b:00:44:01:00:00:01 iaid = 1 static
dhcpd[122762]: Advertise PD: address b1a1:3003:1014:5::/64 to client with duid 00:01:00:01:26:69:f0:4b:00:44:01:00:00:01 iaid = 2 static
dhcpd[122762]: Sending Relay-reply to 2406:3003:1:5a::1 port 547
dhcpd[122762]: send_packet6: Bad file descriptor
dhcpd[122762]: dhcpv6: send_packet6() sent -1 of 177 bytes
dhcpd[122762]: Relay-forward message from 2406:3003:1:5a::1 port 547, link address 2404:e801:1014::1, peer address fe80::244:1ff:fe00:1
dhcpd[122762]: Advertise NA: address 2404:e801:1014::5 to client with duid 00:01:00:01:26:69:f0:4b:00:44:01:00:00:01 iaid = 1 static
dhcpd[122762]: Advertise PD: address b1a1:3003:1014:5::/64 to client with duid 00:01:00:01:26:69:f0:4b:00:44:01:00:00:01 iaid = 2 static
dhcpd[122762]: Sending Relay-reply to 2406:3003:1:5a::1 port 547
dhcpd[122762]: send_packet6: Bad file descriptor
dhcpd[122762]: dhcpv6: send_packet6() sent -1 of 177 bytes

lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 19.10
Release:        19.10
Codename:       eoan
</code>```

答:
the interface used for dhcpv6 server had sub-interfaces too which was being used for some other function.

After the sub-interfaces were deleted, the allocation was successful.

This looks like a limitation/bug, but couldn't find any documentation.

Body:
I have a dhcpv6 server configured on ubuntu. i has static bindings defined for each client based on interface ID.
But when a client solicits, the allocation fails on the DHCPv6 server.
"dhcpd[122762]: send_packet6: Bad file descriptor"

----Config on dhcpv6 server----

subnet6 2404:e801:1014::/48 {
    host client-name-2404.e801.1014.5 {
        host-identifier option dhcp6.interface-id "OLT3923.IOT xpon 0/2/0/1:2404:e801:1014::5";
        fixed-address6 2404:e801:1014::5;
        fixed-prefix6 b1a1:3003:1014:5::/64;
    }

----syslog message----

dhcpd[122762]: Relay-forward message from 2406:3003:1:5a::1 port 547, link address 2404:e801:1014::1, peer address fe80::244:1ff:fe00:1
dhcpd[122762]: Advertise NA: address 2404:e801:1014::5 to client with duid 00:01:00:01:26:69:f0:4b:00:44:01:00:00:01 iaid = 1 static
dhcpd[122762]: Advertise PD: address b1a1:3003:1014:5::/64 to client with duid 00:01:00:01:26:69:f0:4b:00:44:01:00:00:01 iaid = 2 static
dhcpd[122762]: Sending Relay-reply to 2406:3003:1:5a::1 port 547
dhcpd[122762]: send_packet6: Bad file descriptor
dhcpd[122762]: dhcpv6: send_packet6() sent -1 of 177 bytes
dhcpd[122762]: Relay-forward message from 2406:3003:1:5a::1 port 547, link address 2404:e801:1014::1, peer address fe80::244:1ff:fe00:1
dhcpd[122762]: Advertise NA: address 2404:e801:1014::5 to client with duid 00:01:00:01:26:69:f0:4b:00:44:01:00:00:01 iaid = 1 static
dhcpd[122762]: Advertise PD: address b1a1:3003:1014:5::/64 to client with duid 00:01:00:01:26:69:f0:4b:00:44:01:00:00:01 iaid = 2 static
dhcpd[122762]: Sending Relay-reply to 2406:3003:1:5a::1 port 547
dhcpd[122762]: send_packet6: Bad file descriptor
dhcpd[122762]: dhcpv6: send_packet6() sent -1 of 177 bytes

lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 19.10
Release:        19.10
Codename:       eoan


问:
Assign a value to an rvalue reference returned from function
```<code>#include <utility>
template <typename Container>
decltype(auto) index(Container &&arr, int n) {
    return std::forward<Container>(arr)[n];
}
</code>```

Make a function call :

```<code>#include <vector>
index(std::vector {1, 2, 3, 4, 5}, 2) = 0;
</code>```

When function calling finished, the object std::vector {1, 2, 3, 4, 5} will be destroyed, assigning a value to a deallocated address would cause undefined behaviour. But the above code works well and valgrind detected nothing. Maybe the compile helps me make another invisible variable like

```<code>auto &&invisible_value {index(std::vector {1, 2, 3, 4, 5}, 2)};
invisible_value = 9;
</code>```

If my guess is incorrect, I want to know why assigning a value to an rvalue reference returned from function is worked and when the temporary object index(std::vector {1, 2, 3, 4, 5}, 2) will be destroyed.

This idea originated from 《Effective Modern C++》, Item3 : Understand decltype.

答:
invisible_value = 9; is completely legal assignment as 9 is indeed a temporary. rvalue references can be assigned with a temporary but not bound to an lvalue (for example a variable; but you can achieve this like below:

```<code>int a =10;
invisible_value=std::move(a);
</code>```

https://godbolt.org/z/iTNGFr. Mode detailed explanation in this question C++ Double Address Operator? (&&).

edit:

the assignment is only legal if it is in the same scope. invisible_value in this case refers to something that was in the scope of index function and it's behavior is undefined if you have a reference to it.

Body:
#include <utility>
template <typename Container>
decltype(auto) index(Container &&arr, int n) {
    return std::forward<Container>(arr)[n];
}

Make a function call :

#include <vector>
index(std::vector {1, 2, 3, 4, 5}, 2) = 0;

When function calling finished, the object std::vector {1, 2, 3, 4, 5} will be destroyed, assigning a value to a deallocated address would cause undefined behaviour. But the above code works well and valgrind detected nothing. Maybe the compile helps me make another invisible variable like

auto &&invisible_value {index(std::vector {1, 2, 3, 4, 5}, 2)};
invisible_value = 9;

If my guess is incorrect, I want to know why assigning a value to an rvalue reference returned from function is worked and when the temporary object index(std::vector {1, 2, 3, 4, 5}, 2) will be destroyed.

This idea originated from 《Effective Modern C++》, Item3 : Understand decltype.

Body:
invisible_value = 9; is completely legal assignment as 9 is indeed a temporary. rvalue references can be assigned with a temporary but not bound to an lvalue (for example a variable; but you can achieve this like below:

int a =10;
invisible_value=std::move(a);

https://godbolt.org/z/iTNGFr. Mode detailed explanation in this question C++ Double Address Operator? (&&).

edit:

the assignment is only legal if it is in the same scope. invisible_value in this case refers to something that was in the scope of index function and it's behavior is undefined if you have a reference to it.


问:
Scikit-learn LinearRegression: How to resolve the error " fit() missing 1 required positional argument: 'y' "?
My code:

```<code>import pandas as pd
from sklearn.Linear_model import LinearRegression as lr
df = pd.DataFrame({"Match Score":[95,85,80,70,60], "Statistic score":[85,95,70,65,70]})
x =df[["Match Score"]]
y =df["Statistic score"]
lr.fit(x,y)
</code>```

Error details:

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-19-e644bf405118> in <module>
----> 1 lr.fit(x,y)

TypeError: fit() missing 1 required positional argument: 'y'
</code>```

答:
You must instantiate the LinearRegression estimator first.

```<code>my_lr = lr().fit(x,y)
</code>```

You also have a typo in your import statements, it's sklearn.linear_model with a small l.

Body:
My code:

import pandas as pd
from sklearn.Linear_model import LinearRegression as lr
df = pd.DataFrame({"Match Score":[95,85,80,70,60], "Statistic score":[85,95,70,65,70]})
x =df[["Match Score"]]
y =df["Statistic score"]
lr.fit(x,y)

Error details:

TypeError                                 Traceback (most recent call last)
<ipython-input-19-e644bf405118> in <module>
----> 1 lr.fit(x,y)

TypeError: fit() missing 1 required positional argument: 'y'

Body:
You must instantiate the LinearRegression estimator first.

my_lr = lr().fit(x,y)

You also have a typo in your import statements, it's sklearn.linear_model with a small l.


问:
ASP.NET Core client side validation for custom validation attribute on razor page
Currently, this is what my model class looks like, with the custom validation attribute

Client.cs

```<code>    [Required]
    [DisplayName("Bookkeeping")]
    public bool Bookkeeping { get; set; }

    [Required]
    [DisplayName("Personal Income Taxation")]
    public bool Personal_Income_Taxation { get; set; }

    [Required]
    [DisplayName("Self-Employed Business Taxes")]
    public bool Self_Employed_Business_Taxes { get; set; }

    [Required]
    [DisplayName("GST/PST/WCB Returns")]
    public bool GST_PST_WCB_Returns { get; set; }

    [Required]
    [DisplayName("Tax Returns")]
    public bool Tax_Returns { get; set; }

    [Required]
    [DisplayName("Payroll Services")]
    public bool Payroll_Services { get; set; }

    [Required]
    [DisplayName("Previous Year Filings")]
    public bool Previous_Year_Filings { get; set; }

    [Required]
    [DisplayName("Govt. Requisite Form Applicaitons")]
    public bool Government_Requisite_Form_Applications { get; set; }

    [StringLength(220, ErrorMessage = "Cannot exceed more than 220 characters")]
    public string Other { get; set; }

    [CheckboxAndOtherValidation(nameof(Bookkeeping),
nameof(Personal_Income_Taxation),
nameof(Self_Employed_Business_Taxes),
nameof(GST_PST_WCB_Returns),
nameof(Tax_Returns),
nameof(Payroll_Services),
nameof(Previous_Year_Filings),
nameof(Government_Requisite_Form_Applications), ErrorMessage = "At least one of the checkboxes or the 'Other' field must be filled")]
    public bool AreCheckboxesAndOtherValid { get; set; }
</code>```

CheckboxAndOtherValidation.cs

```<code>public class CheckboxAndOtherValidation : ValidationAttribute
{
    readonly object TRUE = true;
    string[] _alltheOtherProperty;

    public CheckboxAndOtherValidation(params string[] alltheOthersProperty)
    {
        _alltheOtherProperty = alltheOthersProperty;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {

        var errorMessage = FormatErrorMessage((validationContext.DisplayName));

        bool IsOtherNull = false;
        bool IsAnyCheckboxChecked = false;

        if (_alltheOtherProperty?.Count() > 0 != true)
        {
            return new ValidationResult(errorMessage);
        }

        var otherPropertyInfo = validationContext.ObjectType.GetProperty(nameof(Client.Other));
        if (otherPropertyInfo != null)
        {
            object otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
            if (otherPropertyValue == null || string.IsNullOrEmpty(otherPropertyValue.ToString()))
            {
                IsOtherNull = true;
            }
        }

        for (var i = 0; i < _alltheOtherProperty.Length; ++i)
        {
            var prop = _alltheOtherProperty[i];
            var propertyInfo = validationContext.ObjectType.GetProperty(prop);
            if (propertyInfo == null)
            {
                continue;
            }

            object propertyValue = propertyInfo.GetValue(validationContext.ObjectInstance, null);
            if (Equals(TRUE, propertyValue))
            {
                IsAnyCheckboxChecked = true;
            }
        }

        if (IsOtherNull && !IsAnyCheckboxChecked)
            return new ValidationResult(errorMessage);
        else
            return ValidationResult.Success;

    }
}
</code>```

I want to be able to have client side validation when submitting a form. All other fields of my form work from the client side except the custom validation that I have, by doing something like this

```

How can I get the custom validation attribute to work the same way? (Note: client side scripting works when I include a file in my razor page called "ValidationScriptsPartial", in which there are references to multiple jquery files. I believe thats how client side validation is happening)

答:
How can I get the custom validation attribute to work the same way?

If you'd like to do same validation logic on client side as you did on custom server-side validation attribute on model property.

You can try to implement custom client-side validation based on your actual requirement, for more information, please refer to this doc:

https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-3.1#custom-client-side-validation

Besides, if possible, you can try to use the [Remote] attribute that also enables us to validate combinations of fields, which might help you achieve same requirement easily.

Body:
Currently, this is what my model class looks like, with the custom validation attribute

Client.cs

    [Required]
    [DisplayName("Bookkeeping")]
    public bool Bookkeeping { get; set; }

    [Required]
    [DisplayName("Personal Income Taxation")]
    public bool Personal_Income_Taxation { get; set; }

    [Required]
    [DisplayName("Self-Employed Business Taxes")]
    public bool Self_Employed_Business_Taxes { get; set; }

    [Required]
    [DisplayName("GST/PST/WCB Returns")]
    public bool GST_PST_WCB_Returns { get; set; }

    [Required]
    [DisplayName("Tax Returns")]
    public bool Tax_Returns { get; set; }

    [Required]
    [DisplayName("Payroll Services")]
    public bool Payroll_Services { get; set; }

    [Required]
    [DisplayName("Previous Year Filings")]
    public bool Previous_Year_Filings { get; set; }

    [Required]
    [DisplayName("Govt. Requisite Form Applicaitons")]
    public bool Government_Requisite_Form_Applications { get; set; }

    [StringLength(220, ErrorMessage = "Cannot exceed more than 220 characters")]
    public string Other { get; set; }

    [CheckboxAndOtherValidation(nameof(Bookkeeping),
nameof(Personal_Income_Taxation),
nameof(Self_Employed_Business_Taxes),
nameof(GST_PST_WCB_Returns),
nameof(Tax_Returns),
nameof(Payroll_Services),
nameof(Previous_Year_Filings),
nameof(Government_Requisite_Form_Applications), ErrorMessage = "At least one of the checkboxes or the 'Other' field must be filled")]
    public bool AreCheckboxesAndOtherValid { get; set; }

CheckboxAndOtherValidation.cs

public class CheckboxAndOtherValidation : ValidationAttribute
{
    readonly object TRUE = true;
    string[] _alltheOtherProperty;

    public CheckboxAndOtherValidation(params string[] alltheOthersProperty)
    {
        _alltheOtherProperty = alltheOthersProperty;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {

        var errorMessage = FormatErrorMessage((validationContext.DisplayName));

        bool IsOtherNull = false;
        bool IsAnyCheckboxChecked = false;

        if (_alltheOtherProperty?.Count() > 0 != true)
        {
            return new ValidationResult(errorMessage);
        }

        var otherPropertyInfo = validationContext.ObjectType.GetProperty(nameof(Client.Other));
        if (otherPropertyInfo != null)
        {
            object otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
            if (otherPropertyValue == null || string.IsNullOrEmpty(otherPropertyValue.ToString()))
            {
                IsOtherNull = true;
            }
        }

        for (var i = 0; i < _alltheOtherProperty.Length; ++i)
        {
            var prop = _alltheOtherProperty[i];
            var propertyInfo = validationContext.ObjectType.GetProperty(prop);
            if (propertyInfo == null)
            {
                continue;
            }

            object propertyValue = propertyInfo.GetValue(validationContext.ObjectInstance, null);
            if (Equals(TRUE, propertyValue))
            {
                IsAnyCheckboxChecked = true;
            }
        }

        if (IsOtherNull && !IsAnyCheckboxChecked)
            return new ValidationResult(errorMessage);
        else
            return ValidationResult.Success;

    }
}

I want to be able to have client side validation when submitting a form. All other fields of my form work from the client side except the custom validation that I have, by doing something like this

How can I get the custom validation attribute to work the same way? (Note: client side scripting works when I include a file in my razor page called "ValidationScriptsPartial", in which there are references to multiple jquery files. I believe thats how client side validation is happening)


问:
Failed to connect azure iot hub with esp8266 using azure-iot-arduino library
I'm trying to connect to azure iot hub with esp8266 using azure-iot-arduino library:
https://github.com/Azure/azure-iot-arduino

I've faced several problems doing that:

1) AzureIoTUtility library. File esp82266/sample_init.cpp function configTime(0, 0, "pool.ntp.org", "time.nist.gov"); doesn't work - after that I'm getting message "Fetching NTP epoch time failed! Waiting 2 seconds to retry." again and again.
It is possible to fix that with configTime( "GMT", "pool.ntp.org", "time.nist.gov" ); function instead of configTime(0, 0, "pool.ntp.org", "time.nist.gov");
Or using initTime function from samd directory.

2) AzureIoTUtility library. File adapters/sslClient_arduino.cpp. function sslClient.connect(ip, port); in sslClient_connect(uint32_t ipAddress, uint16_t port) returns 0 status.
I think it`s some problem with sertificate that is used in the library.
I've tried esp32 example and desktop example (c sdk) and they both work well.

The main goal of my project is to use the arduino iot sdk with Arduino MKRZERO and Ethernet modure.
I'm trying to integrate Ethernet library into arduino iot sdk.
For ssl connection I've tried ArduinoBearSSL library and SSLClient library and had the same result.

答:
I've solved the issue using -DUSE_BALTIMORE_CERT flag
but problem 1 is still exists</p>


问:
componentWillReceiveProps has been renamed
I'm using Material ui SwipeableViews That use ReactSwipableView package, I'm getting this error on the console

react-dom.development.js:12466 Warning: componentWillReceiveProps has been renamed, and is not recommended for use. See  for details.

Move data fetching code or side effects to componentDidUpdate.

If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at:

Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run npx react-codemod rename-unsafe-lifecycles in your project source folder.

Please update the following components: ReactSwipableView

is there any way to get rid of this error i did try UNSAFE_componentWillReceiveProps but nothing change

答:
You can clean the warning by just blocking warning command in node_modules/react-dom/cjs/react-dom.development.js and node_modules/react-dom/umd/react-dom.development.js

Before:

```<code>...

if (componentWillReceivePropsUniqueNames.size > 0) {

    var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames);

    warn('componentWillReceiveProps has been renamed, and is not recommended for use. + ...);
}

...
</code>```

After:

```<code>...

if (componentWillReceivePropsUniqueNames.size > 0) {

    var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames);

    //warn('componentWillReceiveProps has been renamed, and is not recommended for use. + ...);
}

...
</code>```

Body:
You can clean the warning by just blocking warning command in node_modules/react-dom/cjs/react-dom.development.js and node_modules/react-dom/umd/react-dom.development.js

Before:

...

if (componentWillReceivePropsUniqueNames.size > 0) {

    var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames);

    warn('componentWillReceiveProps has been renamed, and is not recommended for use. + ...);
}

...

After:

...

if (componentWillReceivePropsUniqueNames.size > 0) {

    var _sortedNames4 = setToSortedString(componentWillReceivePropsUniqueNames);

    //warn('componentWillReceiveProps has been renamed, and is not recommended for use. + ...);
}

...