问:
Loop through the files in a folder
I have built some code to loop through multiple files in a folder and then try to consolidate in one sheet.

I am mostly able to accomplish that, but it is failing whenever my source file has only one line item to copy.

It is failing at code Range(Selection, Selection.End(xlDown)).Select. I used this to copy entire rows from A7 row. It works when I have more than one line item. But the code fails when I have only one line item.

And also need to help to change the target sheet: I need to paste it into a new workbook.

Below is my code:

```<code>Option explicit

Const FOLDER_PATH = "C:\Users\1\Desktop\New folder (4)\" 'REMEMBER END BACKSLASH

Sub ImportWorksheets()
    '=============================================
    'Process all Excel files in specified folder
    '=============================================
    Dim sFile As String 'file to process
    Dim wsTarget As Worksheet
    Dim wbSource As Workbook
    Dim wsSource As Worksheet
    Dim rowTarget As Long 'output row

    rowTarget = 7

    'check the folder exists
    If Not FileFolderExists(FOLDER_PATH) Then
        MsgBox "Specified folder does not exist, exiting!"
        Exit Sub
    End If

    'reset application settings in event of error
    On Error GoTo errHandler
    Application.ScreenUpdating = False

    'set up the target worksheet
    Set wsTarget = Sheets("Sheet1")

    'loop through the Excel files in the folder
    sFile = Dir(FOLDER_PATH & "*.xls*")
    Do Until sFile = ""

        'open the source file and set the source worksheet - ASSUMED WORKSHEET(1)
        Set wbSource = Workbooks.Open(FOLDER_PATH & sFile)
        Set wsSource = wbSource.Worksheets(1) 'EDIT IF NECESSARY

        'import the data

        With wsTarget
            Range("A7:BI7").Select
            Range(Selection, Selection.End(xlDown)).Select
            Selection.Copy
            Windows("Loop through files.xlsm").Activate
            Range("A2").Select
            Selection.End(xlDown).Select
            ActiveCell.Offset(1, 0).Select
            ActiveSheet.PasteSpecial
        End With

        'close the source workbook, increment the output row and get the next file
        Application.DisplayAlerts = False
        wbSource.Close SaveChanges:=False
        Application.DisplayAlerts = True
        rowTarget = rowTarget + 1
        sFile = Dir()
    Loop

    errHandler:
    On Error Resume Next
    Application.ScreenUpdating = True

    'tidy up
    Set wsSource = Nothing
    Set wbSource = Nothing
    Set wsTarget = Nothing
End Sub

Private Function FileFolderExists(strPath As String) As Boolean
    If Not Dir(strPath, vbDirectory) = vbNullString Then FileFolderExists = True
End Function
</code>```

答:
Try this. If all your workbooks start at A7, and there are no empty columns or rows, .CurrentRegion is much better than trying to figure out first, last row and column

```<code>Option Explicit

    Const FOLDER_PATH = "C:\Users\1\Desktop\New folder (4)\" 'REMEMBER END BACKSLASH

    Sub ImportWorksheets()
        '=============================================
        'Process all Excel files in specified folder
        '=============================================
        Dim sFile As String 'file to process
        Dim wsTarget As Worksheet
        Dim wbSource As Workbook
        Dim wsSource As Worksheet
        Dim rowTarget As Long 'output row

        rowTarget = 7

        'check the folder exists
        If Not FileFolderExists(FOLDER_PATH) Then
            MsgBox "Specified folder does not exist, exiting!"
            Exit Sub
        End If

        'reset application settings in event of error
        On Error GoTo errHandler
        Application.ScreenUpdating = True

        'set up the target worksheet
        Set wsTarget = Sheets("Sheet1")

        'loop through the Excel files in the folder
        sFile = Dir(FOLDER_PATH & "*.xls*")
        Do Until sFile = ""

            'open the source file and set the source worksheet - ASSUMED WORKSHEET(1)
            Set wbSource = Workbooks.Open(FOLDER_PATH & sFile)
            Set wsSource = wbSource.Worksheets(1) 'EDIT IF NECESSARY

            'import the data

            With wsTarget

                Range("A7").CurrentRegion.Copy
                Windows("Loop through files.xlsm").Activate
                Range("A1048576").Select
                Selection.End(xlUp).Select
                ActiveCell.Offset(1, 0).Select
                ActiveSheet.PasteSpecial
            End With

            'close the source workbook, increment the output row and get the next file
            Application.DisplayAlerts = False
            wbSource.Close SaveChanges:=False
            Application.DisplayAlerts = True
            rowTarget = rowTarget + 1
            sFile = Dir()
        Loop

    errHandler:
        On Error Resume Next
        Application.ScreenUpdating = True

        'tidy up
        Set wsSource = Nothing
        Set wbSource = Nothing
        Set wsTarget = Nothing
    End Sub

    Private Function FileFolderExists(strPath As String) As Boolean
        If Not Dir(strPath, vbDirectory) = vbNullString Then FileFolderExists = True
    End Function
</code>```

Title: Loop through the files in a folder

Body:
I have built some code to loop through multiple files in a folder and then try to consolidate in one sheet.

I am mostly able to accomplish that, but it is failing whenever my source file has only one line item to copy.

It is failing at code Range(Selection, Selection.End(xlDown)).Select. I used this to copy entire rows from A7 row. It works when I have more than one line item. But the code fails when I have only one line item.

And also need to help to change the target sheet: I need to paste it into a new workbook.

Below is my code:

Option explicit

Const FOLDER_PATH = "C:\Users\1\Desktop\New folder (4)\" 'REMEMBER END BACKSLASH

Sub ImportWorksheets()
    '=============================================
    'Process all Excel files in specified folder
    '=============================================
    Dim sFile As String 'file to process
    Dim wsTarget As Worksheet
    Dim wbSource As Workbook
    Dim wsSource As Worksheet
    Dim rowTarget As Long 'output row

    rowTarget = 7

    'check the folder exists
    If Not FileFolderExists(FOLDER_PATH) Then
        MsgBox "Specified folder does not exist, exiting!"
        Exit Sub
    End If

    'reset application settings in event of error
    On Error GoTo errHandler
    Application.ScreenUpdating = False

    'set up the target worksheet
    Set wsTarget = Sheets("Sheet1")

    'loop through the Excel files in the folder
    sFile = Dir(FOLDER_PATH & "*.xls*")
    Do Until sFile = ""

        'open the source file and set the source worksheet - ASSUMED WORKSHEET(1)
        Set wbSource = Workbooks.Open(FOLDER_PATH & sFile)
        Set wsSource = wbSource.Worksheets(1) 'EDIT IF NECESSARY

        'import the data

        With wsTarget
            Range("A7:BI7").Select
            Range(Selection, Selection.End(xlDown)).Select
            Selection.Copy
            Windows("Loop through files.xlsm").Activate
            Range("A2").Select
            Selection.End(xlDown).Select
            ActiveCell.Offset(1, 0).Select
            ActiveSheet.PasteSpecial
        End With

        'close the source workbook, increment the output row and get the next file
        Application.DisplayAlerts = False
        wbSource.Close SaveChanges:=False
        Application.DisplayAlerts = True
        rowTarget = rowTarget + 1
        sFile = Dir()
    Loop

    errHandler:
    On Error Resume Next
    Application.ScreenUpdating = True

    'tidy up
    Set wsSource = Nothing
    Set wbSource = Nothing
    Set wsTarget = Nothing
End Sub

Private Function FileFolderExists(strPath As String) As Boolean
    If Not Dir(strPath, vbDirectory) = vbNullString Then FileFolderExists = True
End Function

Body:
Try this. If all your workbooks start at A7, and there are no empty columns or rows, .CurrentRegion is much better than trying to figure out first, last row and column

Option Explicit

    Const FOLDER_PATH = "C:\Users\1\Desktop\New folder (4)\" 'REMEMBER END BACKSLASH

    Sub ImportWorksheets()
        '=============================================
        'Process all Excel files in specified folder
        '=============================================
        Dim sFile As String 'file to process
        Dim wsTarget As Worksheet
        Dim wbSource As Workbook
        Dim wsSource As Worksheet
        Dim rowTarget As Long 'output row

        rowTarget = 7

        'check the folder exists
        If Not FileFolderExists(FOLDER_PATH) Then
            MsgBox "Specified folder does not exist, exiting!"
            Exit Sub
        End If

        'reset application settings in event of error
        On Error GoTo errHandler
        Application.ScreenUpdating = True

        'set up the target worksheet
        Set wsTarget = Sheets("Sheet1")

        'loop through the Excel files in the folder
        sFile = Dir(FOLDER_PATH & "*.xls*")
        Do Until sFile = ""

            'open the source file and set the source worksheet - ASSUMED WORKSHEET(1)
            Set wbSource = Workbooks.Open(FOLDER_PATH & sFile)
            Set wsSource = wbSource.Worksheets(1) 'EDIT IF NECESSARY

            'import the data

            With wsTarget

                Range("A7").CurrentRegion.Copy
                Windows("Loop through files.xlsm").Activate
                Range("A1048576").Select
                Selection.End(xlUp).Select
                ActiveCell.Offset(1, 0).Select
                ActiveSheet.PasteSpecial
            End With

            'close the source workbook, increment the output row and get the next file
            Application.DisplayAlerts = False
            wbSource.Close SaveChanges:=False
            Application.DisplayAlerts = True
            rowTarget = rowTarget + 1
            sFile = Dir()
        Loop

    errHandler:
        On Error Resume Next
        Application.ScreenUpdating = True

        'tidy up
        Set wsSource = Nothing
        Set wbSource = Nothing
        Set wsTarget = Nothing
    End Sub

    Private Function FileFolderExists(strPath As String) As Boolean
        If Not Dir(strPath, vbDirectory) = vbNullString Then FileFolderExists = True
    End Function


来源: stackexchange

问:
Save dta file with local and global variables in file name
In Stata, I try to save a dta file using local and global macros together in file names.

However, the local macros are not parsed correctly.

The global macro result is a folder directory which is:

```<code>global result "C:\Users\...\....\..."
</code>```

The local macro x is defined in a loop:

```<code>foreach x of varlist ret_yyy {
    .......
    save "$result\Reg_Coefficients\`x'", replace
}
</code>```

This only produces a file under a "result" folder with name "Reg_Coefficients`x'".

What I expect is to save a file under folder "Reg_Coefficients".

答:
Use forward slashes (/) instead:</p>

```<code>sysuse auto, clear
global result "C:/Users/.../..../..."

foreach x of varlist * {
    display "$result/Reg_Coefficients/`x'"
}

C:/Users/.../..../.../Reg_Coefficients/make
C:/Users/.../..../.../Reg_Coefficients/price
C:/Users/.../..../.../Reg_Coefficients/mpg
C:/Users/.../..../.../Reg_Coefficients/rep78
C:/Users/.../..../.../Reg_Coefficients/headroom
C:/Users/.../..../.../Reg_Coefficients/trunk
C:/Users/.../..../.../Reg_Coefficients/weight
C:/Users/.../..../.../Reg_Coefficients/length
C:/Users/.../..../.../Reg_Coefficients/turn
C:/Users/.../..../.../Reg_Coefficients/displacement
C:/Users/.../..../.../Reg_Coefficients/gear_ratio
C:/Users/.../..../.../Reg_Coefficients/foreign
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In Stata, I try to save a dta file using local and global macros together in file names.

However, the local macros are not parsed correctly.

The global macro result is a folder directory which is:

global result "C:\Users\...\....\..."

The local macro x is defined in a loop:

foreach x of varlist ret_yyy {
    .......
    save "$result\Reg_Coefficients\`x'", replace
}

This only produces a file under a "result" folder with name "Reg_Coefficients`x'".

What I expect is to save a file under folder "Reg_Coefficients".

Body:
Use forward slashes (/) instead:

sysuse auto, clear
global result "C:/Users/.../..../..."

foreach x of varlist * {
    display "$result/Reg_Coefficients/`x'"
}

C:/Users/.../..../.../Reg_Coefficients/make
C:/Users/.../..../.../Reg_Coefficients/price
C:/Users/.../..../.../Reg_Coefficients/mpg
C:/Users/.../..../.../Reg_Coefficients/rep78
C:/Users/.../..../.../Reg_Coefficients/headroom
C:/Users/.../..../.../Reg_Coefficients/trunk
C:/Users/.../..../.../Reg_Coefficients/weight
C:/Users/.../..../.../Reg_Coefficients/length
C:/Users/.../..../.../Reg_Coefficients/turn
C:/Users/.../..../.../Reg_Coefficients/displacement
C:/Users/.../..../.../Reg_Coefficients/gear_ratio
C:/Users/.../..../.../Reg_Coefficients/foreign


问:
How can I use UserDefaults in Swift?
How can I use UserDefaults to save/retrieve strings, booleans and other data in Swift?</p>

答:
Swift 5 and above:

```<code>let defaults = UserDefaults.standard

defaults.set(25, forKey: "Age")
let savedInteger = defaults.integer(forKey: "Age")

defaults.set(true, forKey: "UseFaceID")
let savedBoolean = defaults.bool(forKey: "UseFaceID")

defaults.set(CGFloat.pi, forKey: "Pi")
defaults.set("Your Name", forKey: "Name")
defaults.set(Date(), forKey: "LastRun")

let array = ["Hello", "World"]
defaults.set(array, forKey: "SavedArray")

let savedArray = defaults.object(forKey: "SavedArray") as? [String] ?? [String()

let dict = ["Name": "Your", "Country": "YourCountry"]
defaults.set(dict, forKey: "SavedDict")

let savedDictionary = defaults.object(forKey: "SavedDictionary") as? [String: String] ?? [String: String]()
</code>```

:)

ContentLicense: CC BY-SA 3.0

Title: How can I use UserDefaults in Swift?

Body:
Swift 5 and above:

let defaults = UserDefaults.standard

defaults.set(25, forKey: "Age")
let savedInteger = defaults.integer(forKey: "Age")

defaults.set(true, forKey: "UseFaceID")
let savedBoolean = defaults.bool(forKey: "UseFaceID")

defaults.set(CGFloat.pi, forKey: "Pi")
defaults.set("Your Name", forKey: "Name")
defaults.set(Date(), forKey: "LastRun")

let array = ["Hello", "World"]
defaults.set(array, forKey: "SavedArray")

let savedArray = defaults.object(forKey: "SavedArray") as? [String] ?? [String()

let dict = ["Name": "Your", "Country": "YourCountry"]
defaults.set(dict, forKey: "SavedDict")

let savedDictionary = defaults.object(forKey: "SavedDictionary") as? [String: String] ?? [String: String]()

:)


问:
Unique identifier for Racket objects?
Is there a way to get a unique identifier for an object in Racket? For instance, when we use Racket's eq? operator to check whether two variables refer to the same object, what identifier is it using to achieve this comparison?

I'm looking for something like python's id function or Ruby's object_id method, in other words, some function id such that (= (id obj) (id obj2)) means that (eq? obj obj2) is true.

Some relevant docs:

Object Identity and Comparisons

Variables and Locations

答:
Is eq-hash-code what you want?

```<code>> (define l1 '(1))
> (define l2 '(1))
> (eq? l1 l2)
#f
> (eq-hash-code l1)
9408
> (eq-hash-code l2)
9412
</code>```

Title: Unique identifier for Racket objects?

Body:
Is eq-hash-code what you want?

> (define l1 '(1))
> (define l2 '(1))
> (eq? l1 l2)
#f
> (eq-hash-code l1)
9408
> (eq-hash-code l2)
9412


问:
Get color from wallpaper? - Android
How can I find the (Average) color of the current wallpaper and set that color to a layout on my widget?

An example of what I'm trying to do:

This is a setting on AccuWeather:

答: You can use WallpaperManager.getWallpaperColors that was added in API 27</p>

Title: Get color from wallpaper? - Android


问:
Why are generics needed when we can do casting to Object class?
We have generics in java using which we can generalize a class.
I know that Object class is the parent class of every class.

When I can typecast to and from Object then why generics are needed?

```<code>class Response<T>{
    T data;
}
</code>```

```<code>class Response{
    Object data;
}
</code>```

Both of the above code snippets will work the same way.

答:
That's how things were done before generics existed: you declared objects of type Object when you didn't know their specific type.

But an Object type doesn't say much, the benefit of generics is that now we know what's the type of the object, as far as it's possible at compile time. Read about type erasure to understand the limitations of the way Generics were implemented in Java.

Body:
We have generics in java using which we can generalize a class.
I know that Object class is the parent class of every class.

When I can typecast to and from Object then why generics are needed?

class Response<T>{
    T data;
}

class Response{
    Object data;
}

Both of the above code snippets will work the same way.


问:
SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall
Hi All I am using spring simple JDBC template to call the oracle procedure the below are my code.

The procedure

```<code>create or replace
PROCEDURE get_all_system_users(
pi_client_code IN VARCHAR2,
po_system_users OUT T_SYSTEM_USER_TAB,
po_error_code        OUT NUMBER,
po_error_description OUT VARCHAR2)
IS
ctr NUMBER;
sysUser SYSTEM_USER_OBJ;
BEGIN
ctr:=0;
po_system_users:= t_system_user_tab();
end
</code>```

The Spring Dao class

```<code>public class ManualSaleStoredProcedureDao {

private SimpleJdbcCall getAllSytemUsers;

public List<SystemUser> getAllSytemUsers(String clientCode) {

    MapSqlParameterSource in = new MapSqlParameterSource();
    in.addValue("pi_client_code", clientCode);
    in.addValue("po_system_users", null,
            OracleTypes.ARRAY, "T_SYSTEM_USER_TAB");

    Map<String, Object> result = getAllSytemUsers.execute(in);

    return null;

}

public void setDataSource(DataSource dataSource) {

    getAllSytemUsers = new SimpleJdbcCall(dataSource)
            .withSchemaName("SChemaName")
            .withProcedureName("get_all_system_users")

            .declareParameters(

                    new SqlParameter(
                            "pi_client_code",
                            OracleTypes.VARCHAR,
                            "pi_client_code"));

}
</code>```

When I am calling Map<String, Object> result = getAllSytemUsers.execute(in);
Iam getting the below exception

```<code>org.springframework.jdbc.UncategorizedSQLException: CallableStatementCallback; uncategorized SQLException for SQL [{call VSC.GET_ALL_SYSTEM_USERS(?, ?, ?, ?)}]; SQL state [99999]; error code [17004]; Invalid column type: 1111; nested exception is java.sql.SQLException: Invalid column type: 1111
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:83)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:1030)
at org.springframework.jdbc.core.JdbcTemplate.call(JdbcTemplate.java:1064)
at org.springframework.jdbc.core.simple.AbstractJdbcCall.executeCallInternal(AbstractJdbcCall.java:388)
at org.springframework.jdbc.core.simple.AbstractJdbcCall.doExecute(AbstractJdbcCall.java:351)
at org.springframework.jdbc.core.simple.SimpleJdbcCall.execute(SimpleJdbcCall.java:181)
at com.budco.vsc.dao.ManualSaleStoredProcedureDao.getAllSytemUsers(ManualSaleStoredProcedureDao.java:30)
at com.budco.vsc.dao.ManualSaleStoredProcedureDaoITest.getCustomerNotes(ManualSaleStoredProcedureDaoITest.java:64)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
   Caused by: java.sql.SQLException: Invalid column type: 1111
at oracle.jdbc.driver.OracleStatement.getInternalType(OracleStatement.java:3950)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameterInternal(OracleCallableStatement.java:135)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:304)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:393)
at oracle.jdbc.driver.OracleCallableStatementWrapper.registerOutParameter(OracleCallableStatementWrapper.java:1569)
at org.apache.commons.dbcp.DelegatingCallableStatement.registerOutParameter(DelegatingCallableStatement.java:95)
at org.apache.commons.dbcp.DelegatingCallableStatement.registerOutParameter(DelegatingCallableStatement.java:95)
at org.springframework.jdbc.core.CallableStatementCreatorFactory$CallableStatementCreatorImpl.createCallableStatement(CallableStatementCreatorFactory.java:198)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:1008)
... 35 more
</code>```

答:
We had the same issue when we had a typo in the mybatis mapping file like

```<code>        ....
        #{column1Name,          jdbcType=INTEGER},
        #{column2Name,          jdbcType=VARCHAR},
        #{column3Name,      jdbcTyep=VARCHAR}  -- do you see the typo ?
        .....
</code>```

So check this kind of typos as well. Unfortunately, it can not understand the typo in compile/build time, it causes an unchecked exception and booms in runtime.

Body:
Hi All I am using spring simple JDBC template to call the oracle procedure the below are my code.

The procedure

create or replace
PROCEDURE get_all_system_users(
pi_client_code IN VARCHAR2,
po_system_users OUT T_SYSTEM_USER_TAB,
po_error_code        OUT NUMBER,
po_error_description OUT VARCHAR2)
IS
ctr NUMBER;
sysUser SYSTEM_USER_OBJ;
BEGIN
ctr:=0;
po_system_users:= t_system_user_tab();
end

The Spring Dao class

public class ManualSaleStoredProcedureDao {

private SimpleJdbcCall getAllSytemUsers;

public List<SystemUser> getAllSytemUsers(String clientCode) {

    MapSqlParameterSource in = new MapSqlParameterSource();
    in.addValue("pi_client_code", clientCode);
    in.addValue("po_system_users", null,
            OracleTypes.ARRAY, "T_SYSTEM_USER_TAB");

    Map<String, Object> result = getAllSytemUsers.execute(in);

    return null;

}

public void setDataSource(DataSource dataSource) {

    getAllSytemUsers = new SimpleJdbcCall(dataSource)
            .withSchemaName("SChemaName")
            .withProcedureName("get_all_system_users")

            .declareParameters(

                    new SqlParameter(
                            "pi_client_code",
                            OracleTypes.VARCHAR,
                            "pi_client_code"));

}

When I am calling Map<String, Object> result = getAllSytemUsers.execute(in);
Iam getting the below exception

org.springframework.jdbc.UncategorizedSQLException: CallableStatementCallback; uncategorized SQLException for SQL [{call VSC.GET_ALL_SYSTEM_USERS(?, ?, ?, ?)}]; SQL state [99999]; error code [17004]; Invalid column type: 1111; nested exception is java.sql.SQLException: Invalid column type: 1111
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:83)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:1030)
at org.springframework.jdbc.core.JdbcTemplate.call(JdbcTemplate.java:1064)
at org.springframework.jdbc.core.simple.AbstractJdbcCall.executeCallInternal(AbstractJdbcCall.java:388)
at org.springframework.jdbc.core.simple.AbstractJdbcCall.doExecute(AbstractJdbcCall.java:351)
at org.springframework.jdbc.core.simple.SimpleJdbcCall.execute(SimpleJdbcCall.java:181)
at com.budco.vsc.dao.ManualSaleStoredProcedureDao.getAllSytemUsers(ManualSaleStoredProcedureDao.java:30)
at com.budco.vsc.dao.ManualSaleStoredProcedureDaoITest.getCustomerNotes(ManualSaleStoredProcedureDaoITest.java:64)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
   Caused by: java.sql.SQLException: Invalid column type: 1111
at oracle.jdbc.driver.OracleStatement.getInternalType(OracleStatement.java:3950)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameterInternal(OracleCallableStatement.java:135)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:304)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:393)
at oracle.jdbc.driver.OracleCallableStatementWrapper.registerOutParameter(OracleCallableStatementWrapper.java:1569)
at org.apache.commons.dbcp.DelegatingCallableStatement.registerOutParameter(DelegatingCallableStatement.java:95)
at org.apache.commons.dbcp.DelegatingCallableStatement.registerOutParameter(DelegatingCallableStatement.java:95)
at org.springframework.jdbc.core.CallableStatementCreatorFactory$CallableStatementCreatorImpl.createCallableStatement(CallableStatementCreatorFactory.java:198)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:1008)
... 35 more

Body:
We had the same issue when we had a typo in the mybatis mapping file like

        ....
        #{column1Name,          jdbcType=INTEGER},
        #{column2Name,          jdbcType=VARCHAR},
        #{column3Name,      jdbcTyep=VARCHAR}  -- do you see the typo ?
        .....

So check this kind of typos as well. Unfortunately, it can not understand the typo in compile/build time, it causes an unchecked exception and booms in runtime.


问:
How can an AnimationAction stop at the last frame without looping in three.js?
I'd like to stop an AnimationAction at the last frame that I've created with morph targets.

https://threejs.org/docs/#api/en/animation/AnimationAction

I've tried animationAction.clampWhenFinished = true; but that doesn't seem to work.

I've looked at older stackoverflow questions and searched through forums but the solutions didn't work.

```<code>var cubeTarget1 = new THREE.BoxGeometry(20, 10, 10);
var cubeTarget2 = new THREE.BoxGeometry(20, 10, 50);
var cubeTarget3 = new THREE.BoxGeometry(60, 10, 10);

cubeGeometry.morphTargets[0] = {name: 't1', vertices: cubeTarget1.vertices};
cubeGeometry.morphTargets[1] = {name: 't2', vertices: cubeTarget2.vertices};
cubeGeometry.morphTargets[2] = {name: 't3', vertices: cubeTarget3.vertices};
</code>```

Is there a way I can do something like: (this doesn't work, it loops back to the first morphTarget)

```<code>var clip1 = THREE.AnimationClip.CreateFromMorphTargetSequence('run', [cubeGeometry.morphTargets[0],cubeGeometry.morphTargets[1]], 30);
var action1 = mixer.clipAction(clip1);
action1.play(); // starts at cubeTarget1 ends at cubeTarget2 (animating between them, without a loop)

// and at a later point I'd like to do

var clip2 = THREE.AnimationClip.CreateFromMorphTargetSequence('run', [cubeGeometry.morphTargets[1],cubeGeometry.morphTargets[2]], 30);
var action2 = mixer.clipAction(clip2);
action2.play(); // starts at cubeTarget2 ends at cubeTarget3 (animating between them, without a loop)
</code>```

Here's my fiddle:
https://jsfiddle.net/foreyez/uy8abk6v/

答:
I looked at the three.js code. And inside LoopOnce the section involving clampWhenFinished doesn't get hit at all.

For now I'll do it in a very crude way until I find a better solution:

```<code>action.setDuration(5).play();
setTimeout(function()
{
    action.paused = true;
},2500); // half of the duration
</code>```

Another way I've been doing is to use morphTargetInfluences and just increment it on an animation loop:

```<code>function animate() {
  if (cube.morphTargetInfluences[0] < 1)
    cube.morphTargetInfluences[0] += 0.01;

  controls.update();
  renderer.render(scene, camera);
  requestAnimationFrame(animate);
}
</code>```

Use Tween.js if you need more functionality.

Body:
I'd like to stop an AnimationAction at the last frame that I've created with morph targets.

https://threejs.org/docs/#api/en/animation/AnimationAction

I've tried animationAction.clampWhenFinished = true; but that doesn't seem to work.

I've looked at older stackoverflow questions and searched through forums but the solutions didn't work.

var cubeTarget1 = new THREE.BoxGeometry(20, 10, 10);
var cubeTarget2 = new THREE.BoxGeometry(20, 10, 50);
var cubeTarget3 = new THREE.BoxGeometry(60, 10, 10);

cubeGeometry.morphTargets[0] = {name: 't1', vertices: cubeTarget1.vertices};
cubeGeometry.morphTargets[1] = {name: 't2', vertices: cubeTarget2.vertices};
cubeGeometry.morphTargets[2] = {name: 't3', vertices: cubeTarget3.vertices};

Is there a way I can do something like: (this doesn't work, it loops back to the first morphTarget)

var clip1 = THREE.AnimationClip.CreateFromMorphTargetSequence('run', [cubeGeometry.morphTargets[0],cubeGeometry.morphTargets[1]], 30);
var action1 = mixer.clipAction(clip1);
action1.play(); // starts at cubeTarget1 ends at cubeTarget2 (animating between them, without a loop)

// and at a later point I'd like to do

var clip2 = THREE.AnimationClip.CreateFromMorphTargetSequence('run', [cubeGeometry.morphTargets[1],cubeGeometry.morphTargets[2]], 30);
var action2 = mixer.clipAction(clip2);
action2.play(); // starts at cubeTarget2 ends at cubeTarget3 (animating between them, without a loop)

Here's my fiddle:
https://jsfiddle.net/foreyez/uy8abk6v/

Body:
I looked at the three.js code. And inside LoopOnce the section involving clampWhenFinished doesn't get hit at all.

For now I'll do it in a very crude way until I find a better solution:

action.setDuration(5).play();
setTimeout(function()
{
    action.paused = true;
},2500); // half of the duration

Another way I've been doing is to use morphTargetInfluences and just increment it on an animation loop:

function animate() {
  if (cube.morphTargetInfluences[0] < 1)
    cube.morphTargetInfluences[0] += 0.01;

  controls.update();
  renderer.render(scene, camera);
  requestAnimationFrame(animate);
}

Use Tween.js if you need more functionality.


问:
How to set environment variables in Jenkins?
I would like to be able to do something like:

```<code>AOEU=$(echo aoeu)
</code>```

and have Jenkins set AOEU=aoeu.

The Environment Variables section in Jenkins doesn't do that. Instead, it sets AOEU='$(echo aoeu)'.

How can I get Jenkins to evaluate a shell command and assign the output to an environment variable?

Eventually, I want to be able to assign the executor of a job to an environment variable that can be passed into or used by other scripts.

答:
This is the snippet to store environment variable and access it.

```<code>node {
   withEnv(["ENABLE_TESTS=true", "DISABLE_SQL=false"]) {
      stage('Select Jenkinsfile') {
          echo "Enable test?: ${env.DEVOPS_SKIP_TESTS}
          customStep script: this
      }
   }
}
</code>```

Note: The value of environment variable is coming as a String. If you want to use it as a boolean then you have to parse it using Boolean.parse(env.DISABLE_SQL).

Body:
I would like to be able to do something like:

AOEU=$(echo aoeu)

and have Jenkins set AOEU=aoeu.

The Environment Variables section in Jenkins doesn't do that. Instead, it sets AOEU='$(echo aoeu)'.

How can I get Jenkins to evaluate a shell command and assign the output to an environment variable?

Eventually, I want to be able to assign the executor of a job to an environment variable that can be passed into or used by other scripts.

Body:
This is the snippet to store environment variable and access it.

node {
   withEnv(["ENABLE_TESTS=true", "DISABLE_SQL=false"]) {
      stage('Select Jenkinsfile') {
          echo "Enable test?: ${env.DEVOPS_SKIP_TESTS}
          customStep script: this
      }
   }
}

Note: The value of environment variable is coming as a String. If you want to use it as a boolean then you have to parse it using Boolean.parse(env.DISABLE_SQL).


问:
Get the difference of two array of objects with multiple constraints
I am trying to get the difference of two arrays of objects, by applying multiple AND constraints.

Find here a small example:

const dbArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company2',
    symbol: 'C2',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company3',
    symbol: 'C3',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company4',
    symbol: 'C4',
    ratingID: '1',
    stockID: '2'
  },
]

const diffArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company6',
    symbol: 'C6',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company1',
    symbol: 'C1',
    ratingID: '5',
    stockID: '3'
  },
  {
    name: 'Company10',
    symbol: 'C10',
    ratingID: '1',
    stockID: '2'
  },
]

const res = diffArr.filter(cv => !dbArr.find(e => e.name === cv.name)).filter(cv => !dbArr.find(e => e.ratingID === cv.ratingID)).filter(cv => !dbArr.find(e => e.stockID === cv.stockID))

console.log(res)

/*
RESULT I would like to get:

const dbArr = [{
  name: 'Company1',
  symbol: 'C1',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company2',
  symbol: 'C2',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company3',
  symbol: 'C3',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company4',
  symbol: 'C4',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company6',
  symbol: 'C6',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company1',
  symbol: 'C1',
  ratingID: '5',
  stockID: '3'
},
{
  name: 'Company10',
  symbol: 'C10',
  ratingID: '1',
  stockID: '2'
},
] */```

As a final result I tried to concatenate multiple finds, however I get an empty array.

However, my method works if I only use find once.

Any suggestions what I am doing wrong?

答:
When you chain multiple .filter's you're essentially saying return only the elements that meet all the conditions; whereas your expected array contains elements that meet any of the diff conditions.

const dbArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company2',
    symbol: 'C2',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company3',
    symbol: 'C3',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company4',
    symbol: 'C4',
    ratingID: '1',
    stockID: '2'
  },
]

const diffArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company6',
    symbol: 'C6',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company1',
    symbol: 'C1',
    ratingID: '5',
    stockID: '3'
  },
  {
    name: 'Company10',
    symbol: 'C10',
    ratingID: '1',
    stockID: '2'
  },
]

const res = diffArr.filter(cv => !dbArr.find(e => e.name === cv.name && e.ratingID === cv.ratingID && e.stockID === cv.stockID));

console.log(res)```
</div>
</div>
</p>

<p>Secondly, you're expected array contains not only the additional elements (elements in <code>diffArr</code> but not <code>dbArr</code>) but also the removed elements (elements in <code>dbArr</code> but not <code>diffArr</code>). To include these elements, you will have to iterate <code>dbArr</code> as well.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const dbArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company2',
    symbol: 'C2',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company3',
    symbol: 'C3',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company4',
    symbol: 'C4',
    ratingID: '1',
    stockID: '2'
  },
];

const diffArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company6',
    symbol: 'C6',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company1',
    symbol: 'C1',
    ratingID: '5',
    stockID: '3'
  },
  {
    name: 'Company10',
    symbol: 'C10',
    ratingID: '1',
    stockID: '2'
  },
];

let same = (cv1, cv2) =>
  cv1.name === cv2.name && cv1.ratingID === cv2.ratingID && cv1.stockID === cv2.stockID;

let res1 = diffArr.filter(cv1 => !dbArr.find(cv2 => same(cv1, cv2)));
let res2 = dbArr.filter(cv1 => !diffArr.find(cv2 => same(cv1, cv2)));
let res = [...res1, ...res2];

console.log(res);</code>```

Another note, find should be replaced with some as its clearer and more aligned with the intention. array.some(predicate) says "do any of the array's elements pass the predicate?"; whereas find says "which is the first element that passes the predicate?"
(mdn)

Body:
I am trying to get the difference of two arrays of objects, by applying multiple AND constraints.

Find here a small example:

const dbArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company2',
    symbol: 'C2',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company3',
    symbol: 'C3',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company4',
    symbol: 'C4',
    ratingID: '1',
    stockID: '2'
  },
]

const diffArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company6',
    symbol: 'C6',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company1',
    symbol: 'C1',
    ratingID: '5',
    stockID: '3'
  },
  {
    name: 'Company10',
    symbol: 'C10',
    ratingID: '1',
    stockID: '2'
  },
]

const res = diffArr.filter(cv => !dbArr.find(e => e.name === cv.name)).filter(cv => !dbArr.find(e => e.ratingID === cv.ratingID)).filter(cv => !dbArr.find(e => e.stockID === cv.stockID))

console.log(res)

/*
RESULT I would like to get:

const dbArr = [{
  name: 'Company1',
  symbol: 'C1',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company2',
  symbol: 'C2',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company3',
  symbol: 'C3',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company4',
  symbol: 'C4',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company6',
  symbol: 'C6',
  ratingID: '1',
  stockID: '2'
},
{
  name: 'Company1',
  symbol: 'C1',
  ratingID: '5',
  stockID: '3'
},
{
  name: 'Company10',
  symbol: 'C10',
  ratingID: '1',
  stockID: '2'
},
] */

As a final result I tried to concatenate multiple finds, however I get an empty array.

However, my method works if I only use find once.

Any suggestions what I am doing wrong?

Body:
When you chain multiple .filter's you're essentially saying return only the elements that meet all the conditions; whereas your expected array contains elements that meet any of the diff conditions.

const dbArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company2',
    symbol: 'C2',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company3',
    symbol: 'C3',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company4',
    symbol: 'C4',
    ratingID: '1',
    stockID: '2'
  },
]

const diffArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company6',
    symbol: 'C6',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company1',
    symbol: 'C1',
    ratingID: '5',
    stockID: '3'
  },
  {
    name: 'Company10',
    symbol: 'C10',
    ratingID: '1',
    stockID: '2'
  },
]

const res = diffArr.filter(cv => !dbArr.find(e => e.name === cv.name && e.ratingID === cv.ratingID && e.stockID === cv.stockID));

console.log(res)

Secondly, you're expected array contains not only the additional elements (elements in diffArr but not dbArr) but also the removed elements (elements in dbArr but not diffArr). To include these elements, you will have to iterate dbArr as well.

const dbArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company2',
    symbol: 'C2',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company3',
    symbol: 'C3',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company4',
    symbol: 'C4',
    ratingID: '1',
    stockID: '2'
  },
];

const diffArr = [{
    name: 'Company1',
    symbol: 'C1',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company6',
    symbol: 'C6',
    ratingID: '1',
    stockID: '2'
  },
  {
    name: 'Company1',
    symbol: 'C1',
    ratingID: '5',
    stockID: '3'
  },
  {
    name: 'Company10',
    symbol: 'C10',
    ratingID: '1',
    stockID: '2'
  },
];

let same = (cv1, cv2) =>
  cv1.name === cv2.name && cv1.ratingID === cv2.ratingID && cv1.stockID === cv2.stockID;

let res1 = diffArr.filter(cv1 => !dbArr.find(cv2 => same(cv1, cv2)));
let res2 = dbArr.filter(cv1 => !diffArr.find(cv2 => same(cv1, cv2)));
let res = [...res1, ...res2];

console.log(res);

Another note, find should be replaced with some as its clearer and more aligned with the intention. array.some(predicate) says "do any of the array's elements pass the predicate?"; whereas find says "which is the first element that passes the predicate?"
(mdn)


问:
Generating random date every month
I have a program running in simulation software that requires generating random date every month.

For e.g: In first time step, let's say first random date is generated for January: 22nd January. It should pick next random date starting from 1st Feb in second time step.

I used following Java code:

```<code>String strDate = dateFormat.format(date());
OrderDate = LocalDate.parse(strDate)
                     .plus(Period.ofDays((1 + new Random().nextInt(30))));
</code>```

The problem is how do I ensure that it picks next date definitely in next month in my second time step. At the moment, it can pick a random date as 5th January and second date as 22nd January. I want to make sure it picks just one date in a single month

答:
Use plusMonths to go into the next month, then use withDayOfMonth to set a random day between 1 and lengthOfMonth:

```<code>LocalDate date = ...;                                    // get from wherever
date = date.plusMonths(1);                               // go 1 month into the future
int maxDay = date.lengthOfMonth();                       // get max possible day
int randomDayOfMonth = new Random().nextInt(maxDay) + 1; // get random day of month
date = date.withDayOfMonth(randomDayOfMonth);            // set random day of month
</code>```

Title: Generating random date every month

Body:
I have a program running in simulation software that requires generating random date every month.

For e.g: In first time step, let's say first random date is generated for January: 22nd January. It should pick next random date starting from 1st Feb in second time step.

I used following Java code:

String strDate = dateFormat.format(date());
OrderDate = LocalDate.parse(strDate)
                     .plus(Period.ofDays((1 + new Random().nextInt(30))));

The problem is how do I ensure that it picks next date definitely in next month in my second time step. At the moment, it can pick a random date as 5th January and second date as 22nd January. I want to make sure it picks just one date in a single month

Body:
Use plusMonths to go into the next month, then use withDayOfMonth to set a random day between 1 and lengthOfMonth:

LocalDate date = ...;                                    // get from wherever
date = date.plusMonths(1);                               // go 1 month into the future
int maxDay = date.lengthOfMonth();                       // get max possible day
int randomDayOfMonth = new Random().nextInt(maxDay) + 1; // get random day of month
date = date.withDayOfMonth(randomDayOfMonth);            // set random day of month


问:
Postgresql how to combine these two queries?
I'm trying to combine these two queries, but I can't figure out how

```<code>SELECT id FROM comments WHERE thread_id = $1 AND parent_id is NULL
</code>```

This returns a integer. i.e - 5

And then use the id result (5) for this recursive query

```<code>With RECURSIVE recursetree AS
(
 SELECT * FROM comments WHERE comment_id = (use the id 5 here)
 UNION
 SELECT t.*
 From comments t
 JOIN recursetree rt ON rt.comment_id = t.parent_id
 )
 SELECT * from recursetree
</code>```

答:
You should be able to put the first query into the anchor of the recursive subquery:

```<code>With RECURSIVE recursetree AS (
      SELECT c.
      FROM comments c
      WHERE thread_id = $1
      UNION ALL
      SELECT c.*
      FROM comments c JOIN
           recursetree
           rt ON rt.comment_id = c.parent_id
     )
SELECT *
FROM recursetree;
</code>```

Also note:

UNION ALL makes more sense than UNION, unless you want to incur the overhead of removing duplicates.

The table alias c makes more sense for comments than the arbitrary letter t.

The $1 suggests that you are munging the query string with a parameter.  You should be using parameters for the query.

Body:
I'm trying to combine these two queries, but I can't figure out how

SELECT id FROM comments WHERE thread_id = $1 AND parent_id is NULL

This returns a integer. i.e - 5

And then use the id result (5) for this recursive query

With RECURSIVE recursetree AS
(
 SELECT * FROM comments WHERE comment_id = (use the id 5 here)
 UNION
 SELECT t.*
 From comments t
 JOIN recursetree rt ON rt.comment_id = t.parent_id
 )
 SELECT * from recursetree

Body:
You should be able to put the first query into the anchor of the recursive subquery:

With RECURSIVE recursetree AS (
      SELECT c.
      FROM comments c
      WHERE thread_id = $1
      UNION ALL
      SELECT c.*
      FROM comments c JOIN
           recursetree
           rt ON rt.comment_id = c.parent_id
     )
SELECT *
FROM recursetree;

Also note:

UNION ALL makes more sense than UNION, unless you want to incur the overhead of removing duplicates.

The table alias c makes more sense for comments than the arbitrary letter t.

The $1 suggests that you are munging the query string with a parameter.  You should be using parameters for the query.


问:
Asynchronous function call in Flex
Is it possible to call a function asynchronously in Flex? I want to parse a file at regular intervals without blocking the rest of the application, what is the recommended approach for this?</p>

答:
The simplest answer is to use the callLater routine - see some documentation here.

```<code>callLater( parseFile, [filename] );

...

public function parseFile( filename : String ) : void
{
    // parse the file
}
</code>```

Another approach is to use the setTimeout call, defined in the flash.utils package.  This one lets you call a routine after a specified amount of time has passed.  Using this routine, you could set up your parseFile function to call itself repeatedly, giving you the regular intervals you were looking for:

```<code>parseFile( filename );

...

public function parseFile( filename : String ) : void
{
    // parse the file

    // call this function again in 5 seconds
    setTimeout( parseFile, 5000, filename );
}
</code>```

OwnerDisplayName: Abdullah Jibaly

ContentLicense: CC BY-SA 2.5

Title: Asynchronous function call in Flex

LastEditorDisplayName: Christophe Herreman

Body:
The simplest answer is to use the callLater routine - see some documentation here.

callLater( parseFile, [filename] );

...

public function parseFile( filename : String ) : void
{
    // parse the file
}

Another approach is to use the setTimeout call, defined in the flash.utils package.  This one lets you call a routine after a specified amount of time has passed.  Using this routine, you could set up your parseFile function to call itself repeatedly, giving you the regular intervals you were looking for:

parseFile( filename );

...

public function parseFile( filename : String ) : void
{
    // parse the file

    // call this function again in 5 seconds
    setTimeout( parseFile, 5000, filename );
}

OwnerDisplayName: Matt Dillard


问:
Simple if statement not working in NodeJS
I wrote a NodeJS app that uses eBay API to get listings from eBay. I'm having an issue where certain items are passing through even though they are supposed to be filtered out with a simple if statement.

The app receives post data from the front end as JSON, executes each search and then filters items out based on certain params. Here is the offending code:

```<code>if ( items[i].listingInfo.listingType != 'Auction' ) {
    //console.log( items[i].listingInfo.listingType );

    if ( items[i].primaryCategory.categoryId == '9355' ) {
        //console.log( items[i].primaryCategory.categoryId );

        if ( price < maxPrice && price > 40 ) {
            //console.log( price, maxPrice );
            file =  path +
                    items[i].itemId + '-' +
                    price + '-' + maxPrice + '-' +
                    items[i].primaryCategory.categoryId + '-' +
                    items[i].listingInfo.listingType;

            if ( !fs.existsSync( file ) ) {
                console.log(
                    'File ' + file + ' does not exist.',
                    !fs.existsSync( file ),
                    items[i].listingInfo.listingType,
                    price < maxPrice,
                    items[i].itemId
                );

                fs.writeFile( file, ' ', function(err) {
                    if (err) {
                        if (debug)
                            console.log('Writing ' + file + ' failed.');
                    }
                    else {
                        if (debug)
                            console.log('Writing ' + file + ' worked.');
                        returnData.success = true;
                        returnData.results[ result.itemId ] = result;
                        console.log( price, maxPrice, !fs.existsSync( file ) );
                        console.log('success');
                    }
                })
            }
            else {
                returnData.discard.file[ result.itemId ] = result;
                delete returnData.results[ result.itemId ];
            }

        }
        else {
            returnData.discard.price[ result.itemId ] = result;
            if (debug)
                console.log('FAILED (price): ' + items[i].itemId + ' is ' + ( price - maxPrice ) + ' greater than maxPrice.');
        }
    }
    else {
        returnData.discard.cat[ result.itemId ] = result;
        if (debug)
            console.log('FAILED (categoryId): ' + items[i].itemId + ' is ' + items[i].primaryCategory.categoryId);
    }
}
else {
    returnData.discard.type[ result.itemId ] = result;
    if (debug)
        console.log('FAILED (listingType): ' + items[i].itemId + ' is a ' + items[i].listingInfo.listingType);
}
</code>```

You can see this line if ( price < maxPrice && price > 40 ) should filter out any items that are greater than the maxPrice and lower than 40. However, it does not do this. I have no idea why it's happening and what is going on here. It seems very simple and straightforward but isn't. Here is the returned object where you can see that it's not working properly.

```<code>111004318957:
    listingType: "FixedPrice"
    maxPrice: 170
    price: 349
</code>```

I'm also using node clusters, so my server.js file has this:

```<code>    function start(route, handle) {
        if ( cluster.isMaster ) {

            for ( var i = 0; i < numCPUs; i++ ) {
                cluster.fork();
            }

            cluster.on('exit', function( worker, code, signal) {
                console.log( 'worker ' + worker.process.pid + ' died' );
            })
        }
        else {
            function onRequest(request, response) {
                var postData = "";
                var pathname = url.parse(request.url).pathname;

                request.setEncoding("utf8");
                request.addListener("data", function(postDataChunk) {
                    postData += postDataChunk;
                });
                request.addListener("end", function() {
                    //console.log('Request ended.');
                    if ( postData != '' ) {
                        postData = JSON.parse(postData);
                    }
                    //console.log(postData.search.searches[0]);
                    route(handle, pathname, response, postData);
                });
            }
            http.createServer(onRequest).listen(8888);
            console.log("Server has started.");
        }
    }
</code>```

Any help here is appreciated, thanks.

EDIT: I should have explained that the 111004318957 is the itemId that is returned by eBay. The result object looks like this:

```<code>results: {
    itemId1: {
        listingType: '',
        maxPrice: '',
        price: ''
    },
    itemId2: {
        listingType: '',
        maxPrice: '',
        price: ''
    }
}
</code>```

EDIT 2: price is set before this code snippet. It's returned in eBay's response and it's location is dependent on items[i].listingInfo.listingType, so there's a simple if/else to set that.

```<code>if ( items[i].listingInfo.listingType == 'AuctionWithBIN' ) {
    price = parseInt( items[i].listingInfo.buyItNowPrice.USD );
}
else {
    price = parseInt( items[i].sellingStatus.currentPrice.USD );
}
</code>```

答:
The author will almost certainly not be able to contribute anything to this question, to clarify if my statement is true or not, as it was asked six years ago.

However, it is fairly certain that the problem has to do with the following part of the code:

```<code>fs.writeFile( file, ' ', function(err) {
  if (err) {
    if (debug)
      console.log('Writing ' + file + ' failed.');
  }
  else {
    if (debug)
      console.log('Writing ' + file + ' worked.');
    returnData.success = true;
    returnData.results[ result.itemId ] = result;
    console.log( price, maxPrice, !fs.existsSync( file ) );
    console.log('success');
  }
})
</code>```

fs.writeFile is async, and if the OP is looping over a list of results, then the result in returnData.results[ result.itemId ] = result will always refer to the last element that loop, no matter if that element matches the condition if ( price < maxPrice && price > 40 ) { or not.

Body:
I wrote a NodeJS app that uses eBay API to get listings from eBay. I'm having an issue where certain items are passing through even though they are supposed to be filtered out with a simple if statement.

The app receives post data from the front end as JSON, executes each search and then filters items out based on certain params. Here is the offending code:

if ( items[i].listingInfo.listingType != 'Auction' ) {
    //console.log( items[i].listingInfo.listingType );

    if ( items[i].primaryCategory.categoryId == '9355' ) {
        //console.log( items[i].primaryCategory.categoryId );

        if ( price < maxPrice && price > 40 ) {
            //console.log( price, maxPrice );
            file =  path +
                    items[i].itemId + '-' +
                    price + '-' + maxPrice + '-' +
                    items[i].primaryCategory.categoryId + '-' +
                    items[i].listingInfo.listingType;

            if ( !fs.existsSync( file ) ) {
                console.log(
                    'File ' + file + ' does not exist.',
                    !fs.existsSync( file ),
                    items[i].listingInfo.listingType,
                    price < maxPrice,
                    items[i].itemId
                );

                fs.writeFile( file, ' ', function(err) {
                    if (err) {
                        if (debug)
                            console.log('Writing ' + file + ' failed.');
                    }
                    else {
                        if (debug)
                            console.log('Writing ' + file + ' worked.');
                        returnData.success = true;
                        returnData.results[ result.itemId ] = result;
                        console.log( price, maxPrice, !fs.existsSync( file ) );
                        console.log('success');
                    }
                })
            }
            else {
                returnData.discard.file[ result.itemId ] = result;
                delete returnData.results[ result.itemId ];
            }

        }
        else {
            returnData.discard.price[ result.itemId ] = result;
            if (debug)
                console.log('FAILED (price): ' + items[i].itemId + ' is ' + ( price - maxPrice ) + ' greater than maxPrice.');
        }
    }
    else {
        returnData.discard.cat[ result.itemId ] = result;
        if (debug)
            console.log('FAILED (categoryId): ' + items[i].itemId + ' is ' + items[i].primaryCategory.categoryId);
    }
}
else {
    returnData.discard.type[ result.itemId ] = result;
    if (debug)
        console.log('FAILED (listingType): ' + items[i].itemId + ' is a ' + items[i].listingInfo.listingType);
}

You can see this line if ( price < maxPrice && price > 40 ) should filter out any items that are greater than the maxPrice and lower than 40. However, it does not do this. I have no idea why it's happening and what is going on here. It seems very simple and straightforward but isn't. Here is the returned object where you can see that it's not working properly.

111004318957:
    listingType: "FixedPrice"
    maxPrice: 170
    price: 349

I'm also using node clusters, so my server.js file has this:

    function start(route, handle) {
        if ( cluster.isMaster ) {

            for ( var i = 0; i < numCPUs; i++ ) {
                cluster.fork();
            }

            cluster.on('exit', function( worker, code, signal) {
                console.log( 'worker ' + worker.process.pid + ' died' );
            })
        }
        else {
            function onRequest(request, response) {
                var postData = "";
                var pathname = url.parse(request.url).pathname;

                request.setEncoding("utf8");
                request.addListener("data", function(postDataChunk) {
                    postData += postDataChunk;
                });
                request.addListener("end", function() {
                    //console.log('Request ended.');
                    if ( postData != '' ) {
                        postData = JSON.parse(postData);
                    }
                    //console.log(postData.search.searches[0]);
                    route(handle, pathname, response, postData);
                });
            }
            http.createServer(onRequest).listen(8888);
            console.log("Server has started.");
        }
    }

Any help here is appreciated, thanks.

EDIT: I should have explained that the 111004318957 is the itemId that is returned by eBay. The result object looks like this:

results: {
    itemId1: {
        listingType: '',
        maxPrice: '',
        price: ''
    },
    itemId2: {
        listingType: '',
        maxPrice: '',
        price: ''
    }
}

EDIT 2: price is set before this code snippet. It's returned in eBay's response and it's location is dependent on items[i].listingInfo.listingType, so there's a simple if/else to set that.

if ( items[i].listingInfo.listingType == 'AuctionWithBIN' ) {
    price = parseInt( items[i].listingInfo.buyItNowPrice.USD );
}
else {
    price = parseInt( items[i].sellingStatus.currentPrice.USD );
}

Body:
The author will almost certainly not be able to contribute anything to this question, to clarify if my statement is true or not, as it was asked six years ago.

However, it is fairly certain that the problem has to do with the following part of the code:

fs.writeFile( file, ' ', function(err) {
  if (err) {
    if (debug)
      console.log('Writing ' + file + ' failed.');
  }
  else {
    if (debug)
      console.log('Writing ' + file + ' worked.');
    returnData.success = true;
    returnData.results[ result.itemId ] = result;
    console.log( price, maxPrice, !fs.existsSync( file ) );
    console.log('success');
  }
})

fs.writeFile is async, and if the OP is looping over a list of results, then the result in returnData.results[ result.itemId ] = result will always refer to the last element that loop, no matter if that element matches the condition if ( price < maxPrice && price > 40 ) { or not.


问:
Need help understanding how the below IIFE code works
I recently came across this javascript code in a competitive site and couldn't understand how this pretty much works.

```<code>var a= 1;
(function(){
    console.log(a);
    var a = 2;
    console.log(a);
})();
</code>```

I expected the output to be..

1 2

But to my surprise, the original output was..

undefined
  2

Can someone please explain how it works? Thanks in advance.

答:
The declaration of variable a is brought to the top of the scope. This process is called hoisting.

```<code>var a= 1;
(function(){
    var a;
    console.log(a);
    a = 2;
    console.log(a);
})();
</code>```

Consider a general snippet without a IIFE and global variable.

function func(){
  console.log(x)
  var x = 2;
  console.log(x)
}
func()```
</div>
</div>
</p>

<p>The declaration of <code>x</code> is hoisted to the top of the scope of the function.So the above code is same as </p>

```function func(){
  var x; //x is declared and its value is undefined
  console.log(x)
  x = 2;
  console.log(x)
}
func()
```

Body:
I recently came across this javascript code in a competitive site and couldn't understand how this pretty much works.

var a= 1;
(function(){
    console.log(a);
    var a = 2;
    console.log(a);
})();

I expected the output to be..

1 2

But to my surprise, the original output was..

undefined
  2

Can someone please explain how it works? Thanks in advance.

Body:
The declaration of variable a is brought to the top of the scope. This process is called hoisting.

var a= 1;
(function(){
    var a;
    console.log(a);
    a = 2;
    console.log(a);
})();

Consider a general snippet without a IIFE and global variable.

function func(){
  console.log(x)
  var x = 2;
  console.log(x)
}
func()

The declaration of x is hoisted to the top of the scope of the function.So the above code is same as

function func(){
  var x; //x is declared and its value is undefined
  console.log(x)
  x = 2;
  console.log(x)
}
func()


问:
The difference between split and re. split
Why the output of second code not printing only 12?</p>

```<code>import re
print(re.split('\d+','On 12th feb 2016, at 11:02 A.M',1))

from re import split
print(split('\d+','On 12th feb 2016, at 11:02 A.M'))

['On ', 'th Jan ', ', at ', ':', ' AM']

['On ', 'th Jan 2016, at 11:02 AM']
</code>```

答:
In your first call to split you are providing an extra parameter '1' which tell the regex engine to only take one split at most. That's why you obtain only one split.

In your second call to split every possible split is accomplished.

Body:
Why the output of second code not printing only 12?

import re
print(re.split('\d+','On 12th feb 2016, at 11:02 A.M',1))

from re import split
print(split('\d+','On 12th feb 2016, at 11:02 A.M'))

['On ', 'th Jan ', ', at ', ':', ' AM']

['On ', 'th Jan 2016, at 11:02 AM']


问:
Express Router redirect after post request gets sent
I have an express route that handles creating new users and I need the page to redirect to /thankyou.html after the user and token get sent.

So I am handling the redirect on the front end but instead of redirecting correctly the browser is showing the JSON user data.

If I test the route through postman everything works as expected on the back end.

I tried redirecting on the express server after the user gets sent and I also tried chaining redirect and send methods. I also added validation to my onreadystatechange to redirect after the proper status code but the page is still redirecting to the JSON data.

Here is my User router.

```<code>const express = require("express");
const router = new express.Router();
const User = require("../models/user");
const client = require("twilio")(process.env.accountSid, process.env.authToken);
const auth = require("../middleware/auth");
const {
  sendWelcomeEmail,
  sendCancellationEmail
} = require("../emails/account");
const multer = require("multer");
const sharp = require("sharp");

router.post("/users", async (req, res) => {
  const user = new User(req.body);
  phone = req.body.phone;
  console.log("Line(18) userRouter req.body", req.body);

  try {
    await user.save();
    sendWelcomeEmail(user.email, user.name);
    const token = await user.generateAuthToken();

    client.calls.create(
      {
        url: "https://example.com/voice/",
        to: phone,
        from: "+17861230774"
      },
      (err, call) => {
        if (!err) {
          process.stdout.write(call.sid);
        }
      }
    );
    res.status(201).send({ user, token });
  } catch (e) {
    res.status(400);
    console.log("User Router Error l:38: ", e);
  }
});

module.exports = router;
</code>```

Here is my Javascript in the front end that is handling the post request.

```<code>// Function to create a new user
const registerButton = document.querySelector("#register");
registerButton.addEventListener("click", event => {
  event.preventDefault();
  var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

  const firstName = document.querySelector("#firstname").value;
  const lastName = document.querySelector("#lastname").value;

  const email = document.querySelector("#email").value;
  const phone = document.querySelector("#phone").value;
  const streetAddress = document.querySelector("#streetaddress").value;
  const zipcode = document.querySelector("#zipcode").value;
  const monthlyBill = document.querySelector("#monthlybill").value;
  const electricProvider = document.querySelector("#electricprovider").value;
  const homeowner = document.querySelector("#homeowner").value;
  console.log(
    firstName,
    lastName,
    email,
    phone,
    streetAddress,
    zipcode,
    monthlyBill,
    electricProvider,
    homeowner
  );
  if (!firstName || !lastName || !email || !phone) {
    alert("Please fill out all fields.");
  } else if (!filter.test(email)) {
    alert("Please provide a valid email address.");
  } else if (phone.length !== 10) {
    alert("Please enter a valid 10 digit phone number");
  } else if (!filter.test(email)) {
    alert("Please provide a valid email address.");
  } else {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/users", true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.send(
      JSON.stringify({
        firstName: firstName,
        lastName: lastName,
        email: email,
        phone: phone,
        zipcode: zipcode,
        electricProvider: electricProvider,
        monthlyBill: monthlyBill,
        streetAddress: streetAddress,
        homeowner: homeowner
      })
    );
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4 && xhr.status === 201) {
        console.log(xhr.responseText);
        window.location = "/thankyou.html";
      }
    };
  }
});
</code>```

I was expecting the browser to redirect to /thankyou.html after the user is created but instead the page is redirecting to /users and rendering the user data. Any tips would be greatly appreciated.

答:
I ended up having to replace window.location as Abderrahim suggested and also remove the validation like this.</p>

```<code> xhr.onreadystatechange = () => {
      window.location.replace("http://localhost/thankyou.html");
      // if (xhr.status === 201) {
      //   console.log(xhr.responseText);
      //   window.location("/thankyou.html");
      // }
    };
</code>```

Body:
I have an express route that handles creating new users and I need the page to redirect to /thankyou.html after the user and token get sent.

So I am handling the redirect on the front end but instead of redirecting correctly the browser is showing the JSON user data.

If I test the route through postman everything works as expected on the back end.

I tried redirecting on the express server after the user gets sent and I also tried chaining redirect and send methods. I also added validation to my onreadystatechange to redirect after the proper status code but the page is still redirecting to the JSON data.

Here is my User router.

const express = require("express");
const router = new express.Router();
const User = require("../models/user");
const client = require("twilio")(process.env.accountSid, process.env.authToken);
const auth = require("../middleware/auth");
const {
  sendWelcomeEmail,
  sendCancellationEmail
} = require("../emails/account");
const multer = require("multer");
const sharp = require("sharp");

router.post("/users", async (req, res) => {
  const user = new User(req.body);
  phone = req.body.phone;
  console.log("Line(18) userRouter req.body", req.body);

  try {
    await user.save();
    sendWelcomeEmail(user.email, user.name);
    const token = await user.generateAuthToken();

    client.calls.create(
      {
        url: "https://example.com/voice/",
        to: phone,
        from: "+17861230774"
      },
      (err, call) => {
        if (!err) {
          process.stdout.write(call.sid);
        }
      }
    );
    res.status(201).send({ user, token });
  } catch (e) {
    res.status(400);
    console.log("User Router Error l:38: ", e);
  }
});

module.exports = router;

Here is my Javascript in the front end that is handling the post request.

// Function to create a new user
const registerButton = document.querySelector("#register");
registerButton.addEventListener("click", event => {
  event.preventDefault();
  var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

  const firstName = document.querySelector("#firstname").value;
  const lastName = document.querySelector("#lastname").value;

  const email = document.querySelector("#email").value;
  const phone = document.querySelector("#phone").value;
  const streetAddress = document.querySelector("#streetaddress").value;
  const zipcode = document.querySelector("#zipcode").value;
  const monthlyBill = document.querySelector("#monthlybill").value;
  const electricProvider = document.querySelector("#electricprovider").value;
  const homeowner = document.querySelector("#homeowner").value;
  console.log(
    firstName,
    lastName,
    email,
    phone,
    streetAddress,
    zipcode,
    monthlyBill,
    electricProvider,
    homeowner
  );
  if (!firstName || !lastName || !email || !phone) {
    alert("Please fill out all fields.");
  } else if (!filter.test(email)) {
    alert("Please provide a valid email address.");
  } else if (phone.length !== 10) {
    alert("Please enter a valid 10 digit phone number");
  } else if (!filter.test(email)) {
    alert("Please provide a valid email address.");
  } else {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/users", true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.send(
      JSON.stringify({
        firstName: firstName,
        lastName: lastName,
        email: email,
        phone: phone,
        zipcode: zipcode,
        electricProvider: electricProvider,
        monthlyBill: monthlyBill,
        streetAddress: streetAddress,
        homeowner: homeowner
      })
    );
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4 && xhr.status === 201) {
        console.log(xhr.responseText);
        window.location = "/thankyou.html";
      }
    };
  }
});

I was expecting the browser to redirect to /thankyou.html after the user is created but instead the page is redirecting to /users and rendering the user data. Any tips would be greatly appreciated.

Body:
I ended up having to replace window.location as Abderrahim suggested and also remove the validation like this.

 xhr.onreadystatechange = () => {
      window.location.replace("http://localhost/thankyou.html");
      // if (xhr.status === 201) {
      //   console.log(xhr.responseText);
      //   window.location("/thankyou.html");
      // }
    };


答:
To generate a random date for a particular month, you need to know the number of days in the month. Use the YearMonth class to work with months.

E.g. to generate random dates for each month of 2019:

```<code>Random random = new Random();
for (int month = 1; month <= 12; month++) {
    YearMonth yearMonth = YearMonth.of(2019, month);
    int daysInMonth = yearMonth.lengthOfMonth();
    int dayOfMonth = random.nextInt(daysInMonth) + 1;
    LocalDate localDate = yearMonth.atDay(dayOfMonth);
    System.out.println(localDate);
}
</code>```

Sample Output

2019-01-12
2019-02-24
2019-03-07
2019-04-28
2019-05-28
2019-06-07
2019-07-20
2019-08-03
2019-09-20
2019-10-31
2019-11-12
2019-12-09
```

<p>If you have a give start date as a string, and want random date in the following month, you can do it like this:</p>

```Random random = new Random();
String strDate = "2019-01-22";

YearMonth nextMonth = YearMonth.from(LocalDate.parse(strDate)).plusMonths(1);
LocalDate orderDate = nextMonth.atDay(random.nextInt(nextMonth.lengthOfMonth()) + 1);

System.out.println(orderDate);
```

<p><em>Sample Output</em></p>

<pre class="lang-none prettyprint-override"><code>2019-02-13
</code>```

Title: Generating random date every month

Body:
To generate a random date for a particular month, you need to know the number of days in the month. Use the YearMonth class to work with months.

E.g. to generate random dates for each month of 2019:

Random random = new Random();
for (int month = 1; month <= 12; month++) {
    YearMonth yearMonth = YearMonth.of(2019, month);
    int daysInMonth = yearMonth.lengthOfMonth();
    int dayOfMonth = random.nextInt(daysInMonth) + 1;
    LocalDate localDate = yearMonth.atDay(dayOfMonth);
    System.out.println(localDate);
}

Sample Output

2019-01-12
2019-02-24
2019-03-07
2019-04-28
2019-05-28
2019-06-07
2019-07-20
2019-08-03
2019-09-20
2019-10-31
2019-11-12
2019-12-09

If you have a give start date as a string, and want random date in the following month, you can do it like this:

Random random = new Random();
String strDate = "2019-01-22";

YearMonth nextMonth = YearMonth.from(LocalDate.parse(strDate)).plusMonths(1);
LocalDate orderDate = nextMonth.atDay(random.nextInt(nextMonth.lengthOfMonth()) + 1);

System.out.println(orderDate);

Sample Output

2019-02-13


问:
Is it normal in scipy.optimise?
I want to optimise my portfolio using Markowitz theory (risk minimization by the Markowitz method for a given income = 15%) and Scipy.minimize

I have risk function

```<code>def objective(x):
    x1=x[0];x2=x[1];x3=x[2]; x4=x[3]
    return 1547.87020*x1**2 + 125.26258*x1*x2 + 1194.3433*x1*x3 + 63.6533*x1*x4  \
    + 27.3176649*x2**2 + 163.28848*x2*x3 + 4.829816*x2*x4 \
    + 392.11819*x3**2 + 56.50518*x3*x4 \
    + 34.484063*x4**2
</code>```

Sum of parts of stocks(in %) = 1

```<code>def constraint1(x):
    return (x[0]+x[1]+x[2]+x[3]-1.0)
</code>```

Income function with restriction

```<code>def constraint2(x):
    return (-1.37458*x[0] + 0.92042*x[1] + 5.06189*x[2] + 0.35974*x[3] - 15.0)
</code>```

And I test it using:

```<code>x0=[0,1,1,0] #Initial value
b=(0.0,1.0)
bnds=(b,b,b,b)
con1={'type':'ineq','fun':constraint1}
con2={'type':'eq','fun':constraint2}
cons=[con1,con2]
sol=minimize(objective,x0,method='SLSQP',\
             bounds=bnds,constraints=cons)
</code>```

And my result is:

```<code>     fun: 678.5433939
     jac: array([1383.25920868,  222.75363159, 1004.03005219,  130.30312347])
 message: 'Positive directional derivative for linesearch'
    nfev: 216
     nit: 20
    njev: 16
  status: 8
 success: False
       x: array([0., 1., 1., 1.])
</code>```

But how? Sum of parts of portfolio cant be more than 1(now parts of stock 2=stock3=stock4=100%). Its constraint1.  Where is problem?

答:
Your code is returning values that do not respect your constraint due to false definition of the first constraint (a-b >= 0 => a>b) so in your case a=1(the order in an inequality is important). On the other hand your x0 must also respect your constraints and sum([0,1,1,0]) = 2 > 1.
I slightly improved your code and fixed the aforementioned issues, but I still think that you need to review your second constraint:

```<code>import numpy as np
from scipy.optimize import minimize

def objective(x):
    x1, x2, x3, x4 = x[0], x[1], x[2], x[3]
    coefficients   = np.array([1547.87020, 125.26258, 1194.3433, 63.6533, 27.3176649, 163.28848, 4.829816, 392.11819, 56.50518, 34.484063])
    xs             = np.array([     x1**2,     x1*x2,     x1*x3,   x1*x4,      x2**2,     x2*x3,    x2*x4,     x3**2,    x3*x4,     x4**2])
    return np.dot(xs, coefficients)

const1 = lambda x: 1 - sum(x)
const2 = lambda x: np.dot(np.array([-1.37458, 0.92042, 5.06189, 0.35974]), x) - 15.0

x0   = [0, 0, 0, 0] #Initial value
b    = (0.0, 1.0)
bnds = (b, b, b, b)
cons = [{'type':'ineq','fun':const1}, {'type':'eq', 'fun':const2}]

# minimize
sol  = minimize(objective,
                x0,
                method      = 'SLSQP',
                bounds      = bnds,
                constraints = cons)

print(sol)
</code>```

output:

```<code>     fun: 392.1181900000138
     jac: array([1194.34332275,  163.28847885,  784.23638535,   56.50518036])
 message: 'Positive directional derivative for linesearch'
    nfev: 92
     nit: 11
    njev: 7
  status: 8
 success: False
       x: array([0.00000000e+00, 5.56638069e-14, 1.00000000e+00, 8.29371293e-14])
</code>```

Title: Is it normal in scipy.optimise?

Body:
I want to optimise my portfolio using Markowitz theory (risk minimization by the Markowitz method for a given income = 15%) and Scipy.minimize

I have risk function

def objective(x):
    x1=x[0];x2=x[1];x3=x[2]; x4=x[3]
    return 1547.87020*x1**2 + 125.26258*x1*x2 + 1194.3433*x1*x3 + 63.6533*x1*x4  \
    + 27.3176649*x2**2 + 163.28848*x2*x3 + 4.829816*x2*x4 \
    + 392.11819*x3**2 + 56.50518*x3*x4 \
    + 34.484063*x4**2

Sum of parts of stocks(in %) = 1

def constraint1(x):
    return (x[0]+x[1]+x[2]+x[3]-1.0)

Income function with restriction

def constraint2(x):
    return (-1.37458*x[0] + 0.92042*x[1] + 5.06189*x[2] + 0.35974*x[3] - 15.0)

And I test it using:

x0=[0,1,1,0] #Initial value
b=(0.0,1.0)
bnds=(b,b,b,b)
con1={'type':'ineq','fun':constraint1}
con2={'type':'eq','fun':constraint2}
cons=[con1,con2]
sol=minimize(objective,x0,method='SLSQP',\
             bounds=bnds,constraints=cons)

And my result is:

     fun: 678.5433939
     jac: array([1383.25920868,  222.75363159, 1004.03005219,  130.30312347])
 message: 'Positive directional derivative for linesearch'
    nfev: 216
     nit: 20
    njev: 16
  status: 8
 success: False
       x: array([0., 1., 1., 1.])

But how? Sum of parts of portfolio cant be more than 1(now parts of stock 2=stock3=stock4=100%). Its constraint1.  Where is problem?

Body:
Your code is returning values that do not respect your constraint due to false definition of the first constraint (a-b >= 0 => a>b) so in your case a=1(the order in an inequality is important). On the other hand your x0 must also respect your constraints and sum([0,1,1,0]) = 2 > 1.
I slightly improved your code and fixed the aforementioned issues, but I still think that you need to review your second constraint:

import numpy as np
from scipy.optimize import minimize

def objective(x):
    x1, x2, x3, x4 = x[0], x[1], x[2], x[3]
    coefficients   = np.array([1547.87020, 125.26258, 1194.3433, 63.6533, 27.3176649, 163.28848, 4.829816, 392.11819, 56.50518, 34.484063])
    xs             = np.array([     x1**2,     x1*x2,     x1*x3,   x1*x4,      x2**2,     x2*x3,    x2*x4,     x3**2,    x3*x4,     x4**2])
    return np.dot(xs, coefficients)

const1 = lambda x: 1 - sum(x)
const2 = lambda x: np.dot(np.array([-1.37458, 0.92042, 5.06189, 0.35974]), x) - 15.0

x0   = [0, 0, 0, 0] #Initial value
b    = (0.0, 1.0)
bnds = (b, b, b, b)
cons = [{'type':'ineq','fun':const1}, {'type':'eq', 'fun':const2}]

# minimize
sol  = minimize(objective,
                x0,
                method      = 'SLSQP',
                bounds      = bnds,
                constraints = cons)

print(sol)

output:

     fun: 392.1181900000138
     jac: array([1194.34332275,  163.28847885,  784.23638535,   56.50518036])
 message: 'Positive directional derivative for linesearch'
    nfev: 92
     nit: 11
    njev: 7
  status: 8
 success: False
       x: array([0.00000000e+00, 5.56638069e-14, 1.00000000e+00, 8.29371293e-14])


问:
SQL query to get max of a column and display with every row
Here's my scenario...
Multiple Items with multiple item types which have multiple prices.
Want to select Items with all types showing the MAX price. Can't figure out how to get the max?

Input:

```<code>ProductId   ProductType Description     Price
</code>```

1           A           BAKED BEANS     1.29

1           B           BAKED BEANS     1.98

Output:

```<code>ProductId   ProductType Description     Price
</code>```

1           A           BAKED BEANS     1.98

1           B           BAKED BEANS     1.98

Any suggestions?

答:
Try this:

```<code>SELECT ProductId,
    ProductType,
    Description,
    b.price
  FROM <YOUR_TABLE> a,
        (SELECT MAX(price) price FROM <YOUR_TABLE>) b
</code>```

For those who love ANSI syntax:

```<code>SELECT ProductId,
    ProductType,
    Description,
    b.price
  FROM <YOUR_TABLE> a INNER JOIN
    (SELECT MAX(price) price FROM <YOUR_TABLE>) b
   ON 1=1
</code>```

Body:
Here's my scenario...
Multiple Items with multiple item types which have multiple prices.
Want to select Items with all types showing the MAX price. Can't figure out how to get the max?

Input:

ProductId   ProductType Description     Price

1           A           BAKED BEANS     1.29

1           B           BAKED BEANS     1.98

Output:

ProductId   ProductType Description     Price

1           A           BAKED BEANS     1.98

1           B           BAKED BEANS     1.98

Any suggestions?

Body:
Try this:

SELECT ProductId,
    ProductType,
    Description,
    b.price
  FROM <YOUR_TABLE> a,
        (SELECT MAX(price) price FROM <YOUR_TABLE>) b

For those who love ANSI syntax:

SELECT ProductId,
    ProductType,
    Description,
    b.price
  FROM <YOUR_TABLE> a INNER JOIN
    (SELECT MAX(price) price FROM <YOUR_TABLE>) b
   ON 1=1


答: Casting(Boxing and Unboxing) is an expensive run-time operation. Generics incur no run-time overhead.</p>

Title: Why are generics needed when we can do casting to Object class?

Body:
We have generics in java using which we can generalize a class.
I know that Object class is the parent class of every class.

When I can typecast to and from Object then why generics are needed?

class Response<T>{
    T data;
}

class Response{
    Object data;
}

Both of the above code snippets will work the same way.


问:
Python NumPy adding [] after operator such as where
I'm super new to python. I'm trying to understand some code. The code uses the NumPy library to analyze a data stream. </p>

```<code>in0 = input_items[0]
mask = np.where(in0 > 0.9)[0]
(start, stop) = (mask[0], mask[-1])
blank = int(50e-6*sample_rate) # Skip first 50 us.
start = start+blank
foo = in1[start:stop] > 0.5
preamble_location = np.where(foo)[0][0]
</code>```

<p>In the second line np.where returns where the elements of in0 are greater than 0.9. What I don't understand is what the [0] in that line does. Similar to the last line I'm not sure what [0][0] does as well. </p>

答:
Suppose you have the following array in0. np.where(in0 > 0.9) will return you a tuple of indices.

```<code>in0 = np.array([0.1, 0.5, 0.95, 1.3, 0.5, 0.2])
</code>```

This can be checked by printing the type

```<code>print (type(np.where(in0 > 0.9)))
# <class 'tuple'>
</code>```

The length of this tuple is 1

```<code>print (len(np.where(in0 > 0.9)))
# 1
</code>```

Now you need the indices of in0 array which fulfill this condition. But np.where returns a tuple.

```<code>print (np.where(in0 > 0.9))
# (array([2, 3]),)
</code>```

To get the list of indices, you need to use the index [0]

```<code>print (np.where(in0 > 0.9)[0])
# [2 3]
</code>```

Now let's come to the second question about [0][0]. Consider the following example:

```<code>foo = in0[0:4] > 0.5
print (foo)

# array([False, False,  True,  True])
</code>```

Now np.where again returns a tuple as shown above. To get the array of indices, you need to access it using index [0]. This will return

```<code>preamble_location = np.where(foo)[0]
print (preamble_location)
# [2 3]
</code>```

Now [0][0] will just return the first element of this array of indices, which is the value 2. If you use [0][1], you will get the second element i.e., 3.

```<code>preamble_location = np.where(foo)[0][0]
print (preamble_location)
# 2
</code>```

Body:
I'm super new to python. I'm trying to understand some code. The code uses the NumPy library to analyze a data stream.

in0 = input_items[0]
mask = np.where(in0 > 0.9)[0]
(start, stop) = (mask[0], mask[-1])
blank = int(50e-6*sample_rate) # Skip first 50 us.
start = start+blank
foo = in1[start:stop] > 0.5
preamble_location = np.where(foo)[0][0]

In the second line np.where returns where the elements of in0 are greater than 0.9. What I don't understand is what the [0] in that line does. Similar to the last line I'm not sure what [0][0] does as well.

Body:
Suppose you have the following array in0. np.where(in0 > 0.9) will return you a tuple of indices.

in0 = np.array([0.1, 0.5, 0.95, 1.3, 0.5, 0.2])

This can be checked by printing the type

print (type(np.where(in0 > 0.9)))
# <class 'tuple'>

The length of this tuple is 1

print (len(np.where(in0 > 0.9)))
# 1

Now you need the indices of in0 array which fulfill this condition. But np.where returns a tuple.

print (np.where(in0 > 0.9))
# (array([2, 3]),)

To get the list of indices, you need to use the index [0]

print (np.where(in0 > 0.9)[0])
# [2 3]

Now let's come to the second question about [0][0]. Consider the following example:

foo = in0[0:4] > 0.5
print (foo)

# array([False, False,  True,  True])

Now np.where again returns a tuple as shown above. To get the array of indices, you need to access it using index [0]. This will return

preamble_location = np.where(foo)[0]
print (preamble_location)
# [2 3]

Now [0][0] will just return the first element of this array of indices, which is the value 2. If you use [0][1], you will get the second element i.e., 3.

preamble_location = np.where(foo)[0][0]
print (preamble_location)
# 2


问:
How to check for truthy values but without skipping the 0?
I have a calculation script for a box and only one little problem: I can't make both conditions A) and B) work at the same time.

A) If I leave the amount of kilometres empty, I want the calculation script to deliver an empty output as well.

B) If I fill in a 0 as the amount of kilometres, I want the calculation script to deliver a 0 as an output as well.

(boxes are formatted as a number and a 0 will always be displayed like "0,00")

Can someone spot my mistake?

```<code>var v1 = +getField("amount_km").value;

if (v1 || v1 === 0) {
    event.value = 0.3 * (v1);
}
else {
    event.value = "";
}
</code>```

答:
This code handles the empty string case:</p>

```<code>var v1 = getField("amount_km").value;
var numV1 = +v1;

if (v1 && (numV1  || numV1 === 0)) {
    event.value = 0.3 * (v1);
} else {
    event.value = "";
}
</code>```

Body:
I have a calculation script for a box and only one little problem: I can't make both conditions A) and B) work at the same time.

A) If I leave the amount of kilometres empty, I want the calculation script to deliver an empty output as well.

B) If I fill in a 0 as the amount of kilometres, I want the calculation script to deliver a 0 as an output as well.

(boxes are formatted as a number and a 0 will always be displayed like "0,00")

Can someone spot my mistake?

var v1 = +getField("amount_km").value;

if (v1 || v1 === 0) {
    event.value = 0.3 * (v1);
}
else {
    event.value = "";
}

Body:
This code handles the empty string case:

var v1 = getField("amount_km").value;
var numV1 = +v1;

if (v1 && (numV1  || numV1 === 0)) {
    event.value = 0.3 * (v1);
} else {
    event.value = "";
}


问:
Is nonatomic worth it?
I've seen many times @property defined as nonatomic for performance reasons. Is there any evidence that this is worth it?</p>

答: When a property is not declared as nonatomic, the synthesized accessor will use locks to ensure that the property is thread-safe. When a lock is unnecessarily used, it adds unneeded messages to your program. The locking operation itself should also be atomic, which means that the processor will lock the memory bus. This can slow down your program as well as others. If a property is not frequently accessed, you probably won't notice a difference, but you definitely want to use it if the property will be used frequently. Overall, though, why not use it? It is a few extra characters which could potentially cause your program to speed up.

Title: Is nonatomic worth it?


问:
Why are generics needed when we can do casting to Object class?
We have generics in java using which we can generalize a class.
I know that Object class is the parent class of every class.

When I can typecast to and from Object then why generics are needed?

```<code>class Response<T>{
    T data;
}
</code>```

```<code>class Response{
    Object data;
}
</code>```

Both of the above code snippets will work the same way.

答:
I can make a list in the "pre-generic" way and do something terrible like this. The result is I can't know the type of the object I get from the list without resorting to reflection.

```<code>List myList = new ArrayList();
myList.add(new Integer(1));
myList.add(new Cat());

Object whatIsThis = myList.get(1);
</code>```

With generics, I can say

```<code>List<Cat> myList = new ArrayList();
myList.add(new Cat());
myList.add(new Integer(1));  // compile time error
myList.add(new Dog()); // compile time error

Cat whatIsThis = myList.get(1); // I *know* this must be a Cat
</code>```

Body:
I can make a list in the "pre-generic" way and do something terrible like this. The result is I can't know the type of the object I get from the list without resorting to reflection.

List myList = new ArrayList();
myList.add(new Integer(1));
myList.add(new Cat());

Object whatIsThis = myList.get(1);

With generics, I can say

List<Cat> myList = new ArrayList();
myList.add(new Cat());
myList.add(new Integer(1));  // compile time error
myList.add(new Dog()); // compile time error

Cat whatIsThis = myList.get(1); // I *know* this must be a Cat


问:
Dynamic progress bar in WooCommerce
I use the code that shows the message "Your current order total is% s to place your order" on the shopping cart page and locks the button until the customer has collected the right amount of products for a certain amount.

Here is the code:

```<code>/* Set a minimum order amount for checkout */
add_action( 'woocommerce_checkout_process', 'wc_minimum_order_amount' );
add_action( 'woocommerce_before_cart' , 'wc_minimum_order_amount' );

function wc_minimum_order_amount() {
    // Set this variable to specify a minimum order value
    $minimum = 1000;

    if ( WC()->cart->total < $minimum ) {

        if( is_cart() ) {

            wc_print_notice(
                sprintf( 'Your current order total is %s — you must have an order with a minimum of %s to place your order ' ,
                    wc_price( WC()->cart->total ),
                    wc_price( $minimum )
                ), 'error'
            );

        } else {

            wc_add_notice(
                sprintf( 'Your current order total is %s — you must have an order with a minimum of %s to place your order' ,
                    wc_price( WC()->cart->total ),
                    wc_price( $minimum )
                ), 'error'
            );

        }
    }
}
</code>```

How can a progress bar be made based on this code? To the client clearly showed what the minimum amount of the order and how much he added products.

For example, based on this: Dynamic Progress Bar with Labels

I could not find anything like this for WooCommerce. I hope this code is useful to many developers.

答:
As option you can make this with JavaScript.
When your site loading cart page, print JS code with current order total through hooks or change template page.
Next, when button with quantity selector is updated, you show progress bar with needed data.</p>

Title: Dynamic progress bar in WooCommerce

Body:
I use the code that shows the message "Your current order total is% s to place your order" on the shopping cart page and locks the button until the customer has collected the right amount of products for a certain amount.

Here is the code:

/* Set a minimum order amount for checkout */
add_action( 'woocommerce_checkout_process', 'wc_minimum_order_amount' );
add_action( 'woocommerce_before_cart' , 'wc_minimum_order_amount' );

function wc_minimum_order_amount() {
    // Set this variable to specify a minimum order value
    $minimum = 1000;

    if ( WC()->cart->total < $minimum ) {

        if( is_cart() ) {

            wc_print_notice(
                sprintf( 'Your current order total is %s — you must have an order with a minimum of %s to place your order ' ,
                    wc_price( WC()->cart->total ),
                    wc_price( $minimum )
                ), 'error'
            );

        } else {

            wc_add_notice(
                sprintf( 'Your current order total is %s — you must have an order with a minimum of %s to place your order' ,
                    wc_price( WC()->cart->total ),
                    wc_price( $minimum )
                ), 'error'
            );

        }
    }
}

How can a progress bar be made based on this code? To the client clearly showed what the minimum amount of the order and how much he added products.

For example, based on this: Dynamic Progress Bar with Labels

I could not find anything like this for WooCommerce. I hope this code is useful to many developers.