问:
Pass a class member from a sub to another
It's a simple question with an easy workaround, but it would make my code simpler if there is a solution.

My actual code, which works, is of this type:

```<code>Sub test()

If Condition Then

    Set classmember = New Class1
    *Instructions to execute with classmember*

    Else: classmember = New class2
    *Instructions to execute with classmember*

End If

End Sub
</code>```

I'd like to excute the instructions in a separate sub. If I do, my classmember is set back to variant when I switch to the other sub, even with static.
I tried to execute a function(classmember) to pass the classmember, the object doesn't support the method.

It works when I declare it public, but it's a temporary variable to create dictionary entries. Adding an entry to the dictionary and removing the item also works, but I'm looking for a solution in the general case.

If there is none, I guess a public dictionary/collection for all the temp variables would be an acceptable solution ?

Real code below :

```<code>Sub peupler_dictionnaire_configs()

For iLigneAnnuaireWs = 3 To 22          '

    Select Case WsCfg.Cells(iLigneAnnuaireWs, 11)

        Case "nautique"

        Set CfgTemp as New Cfg_Naut  'temp class member to populate the DictCfg dictionary

     End Select

Cfgtemp.AdresseCfg(1, 1) = WsCfg.Cells(iLigneAnnuaireWs, 4).Value
Cfgtemp.AdresseCfg(1, 2) = WsCfg.Cells(iLigneAnnuaireWs, 5).Value
Cfgtemp.AdresseCfg(2, 1) = WsCfg.Cells(iLigneAnnuaireWs, 6).Value
Cfgtemp.AdresseCfg(2, 2) = WsCfg.Cells(iLigneAnnuaireWs, 7).Value

Cfgtemp.Read_Cfg

'add entry to dictionary
 DictCfg.Add WsCfg.Cells(iLigneAnnuaireWs, 1), Cfgtemp

'reset of the temp class member
 Set CfgNautTemp = Nothing

Next iLigneAnnuaireWs

End Sub
</code>```

答:
Looks like a case for inheritance.

You'll want a parent level interface class, which has all the common functions from Class1 and Class2; let's call it ParentClass.

As an example, let's say you've got a single common function, which takes no arguments, and returns a string.

Class ParentClass would have this code:

```<code>Function testFunction() As String
End Function
</code>```

Class Class1 would then implement ParentClass, and all its functions (in addition to whatever functions are specific to Class1. To implement a function, you prefix it with the name of the parent class.

So, the code for class Class1 could look like this:

```<code>Implements ParentClass

Function ParentClass_testFunction() As String
    ParentClass_testFunction = "Hello world! I'm the first child!"
End Function
</code>```

The code for Class2 could look like this:

```<code>Implements ParentClass

Function ParentClass_testFunction() As String
    ParentClass_testFunction = "Hello world! I'm the second child!"
End Function
</code>```

In your main code, you would dim your variable as a ParentClass, and when you actually create an instance, you would use your child classes.

For example, this code first prints "Hello world! I'm the first child!", then "Hello world! I'm the second child!".

```<code>Dim x As ParentClass

Set x = New Class1
MsgBox x.testFunction

Set x = New Class2
MsgBox x.testFunction
</code>```

Using a Dim statement to create the variable is the key here; if you don't dim it, it's automatically created as a variant, and that's what you'll see in any functions that you pass it to.

Body:
It's a simple question with an easy workaround, but it would make my code simpler if there is a solution.

My actual code, which works, is of this type:

Sub test()

If Condition Then

    Set classmember = New Class1
    *Instructions to execute with classmember*

    Else: classmember = New class2
    *Instructions to execute with classmember*

End If

End Sub

I'd like to excute the instructions in a separate sub. If I do, my classmember is set back to variant when I switch to the other sub, even with static.
I tried to execute a function(classmember) to pass the classmember, the object doesn't support the method.

It works when I declare it public, but it's a temporary variable to create dictionary entries. Adding an entry to the dictionary and removing the item also works, but I'm looking for a solution in the general case.

If there is none, I guess a public dictionary/collection for all the temp variables would be an acceptable solution ?

Real code below :

Sub peupler_dictionnaire_configs()

For iLigneAnnuaireWs = 3 To 22          '

    Select Case WsCfg.Cells(iLigneAnnuaireWs, 11)

        Case "nautique"

        Set CfgTemp as New Cfg_Naut  'temp class member to populate the DictCfg dictionary

     End Select

Cfgtemp.AdresseCfg(1, 1) = WsCfg.Cells(iLigneAnnuaireWs, 4).Value
Cfgtemp.AdresseCfg(1, 2) = WsCfg.Cells(iLigneAnnuaireWs, 5).Value
Cfgtemp.AdresseCfg(2, 1) = WsCfg.Cells(iLigneAnnuaireWs, 6).Value
Cfgtemp.AdresseCfg(2, 2) = WsCfg.Cells(iLigneAnnuaireWs, 7).Value

Cfgtemp.Read_Cfg

'add entry to dictionary
 DictCfg.Add WsCfg.Cells(iLigneAnnuaireWs, 1), Cfgtemp

'reset of the temp class member
 Set CfgNautTemp = Nothing

Next iLigneAnnuaireWs

End Sub

Body:
Looks like a case for inheritance.

You'll want a parent level interface class, which has all the common functions from Class1 and Class2; let's call it ParentClass.

As an example, let's say you've got a single common function, which takes no arguments, and returns a string.

Class ParentClass would have this code:

Function testFunction() As String
End Function

Class Class1 would then implement ParentClass, and all its functions (in addition to whatever functions are specific to Class1. To implement a function, you prefix it with the name of the parent class.

So, the code for class Class1 could look like this:

Implements ParentClass

Function ParentClass_testFunction() As String
    ParentClass_testFunction = "Hello world! I'm the first child!"
End Function

The code for Class2 could look like this:

Implements ParentClass

Function ParentClass_testFunction() As String
    ParentClass_testFunction = "Hello world! I'm the second child!"
End Function

In your main code, you would dim your variable as a ParentClass, and when you actually create an instance, you would use your child classes.

For example, this code first prints "Hello world! I'm the first child!", then "Hello world! I'm the second child!".

Dim x As ParentClass

Set x = New Class1
MsgBox x.testFunction

Set x = New Class2
MsgBox x.testFunction

Using a Dim statement to create the variable is the key here; if you don't dim it, it's automatically created as a variant, and that's what you'll see in any functions that you pass it to.


来源: stackexchange

问:
which one is more time complexity between TSP or CPP?
What's the difference between traveling-salesman problem and Chinese postman problem From a Time complexity perspective?
I mean which one is more time complexity between TSP and CPP ? </p>

答:
Chinese postman problem can be solved in polynomial time (https://en.wikipedia.org/wiki/Route_inspection_problem), TSP is NP complete (https://en.wikipedia.org/wiki/Travelling_salesman_problem).

So unless P=NP, the travelling salesman problem has a higher time complexity.

ContentLicense: CC BY-SA 4.0


问:
How to check whether date is in past or not in moment js?
After going through lots of links, I could not find a condition that satisfy past date.

It should include today date as well.

```<code>todays_date = 2020-02-19T00:00:00.000Z
</code>```

Something like this:

```<code>moment(2020-02-19T00:00:00.000Z).isBefore();
</code>```

How can I write a condition that includes today's date, past date and return true/false.

答:
Try this

```<code>const dateFormat = 'D MMM'
const isPast = date => moment(date, dateFormat).isBefore(moment(), 'day')
</code>```

you can change the format date

Body:
After going through lots of links, I could not find a condition that satisfy past date.

It should include today date as well.

todays_date = 2020-02-19T00:00:00.000Z

Something like this:

moment(2020-02-19T00:00:00.000Z).isBefore();

How can I write a condition that includes today's date, past date and return true/false.

Body:
Try this

const dateFormat = 'D MMM'
const isPast = date => moment(date, dateFormat).isBefore(moment(), 'day')

you can change the format date


问:
Coin Chane - Dynamic Programming - How read all solutions from the DP table
I have seen different solutions to the same problem, but none of them seem to use the approach I used. So here I'm trying to solve the classical coin-change problem in a bottom up dynamic programming approach using a DP table.

```<code>    int[][] dp = new int[nums.length+1][target+1];
    for (int i = 0; i <= nums.length; ++i)
        dp[i][0] = 1;

    for (int i = 1; i < dp.length; ++i) {
        for (int j = 1; j < dp[i].length; ++j) {
            if (nums[i-1] <= j)
                dp[i][j] = dp[i-1][j] + dp[i][j-nums[i-1]];
            else
                dp[i][j] = dp[i-1][j];
        }
    }
</code>```

The above code generates the table. For fun if I have: {2,3,5} coins, and want to exchange 8, the table would look like:

```<code>1 0 0 0 0 0 0 0 0
1 0 1 0 1 0 1 0 1
1 0 1 1 1 1 2 1 2
1 0 1 1 1 2 2 2 3
</code>```

For the above the following method seem to be working well:

```<code>current <- 4
while (current > 0) do
    i <- current
    j <- 8
    while (j > 0) do
        if (dp[i][j] != dp[i-1][j]) then
            nums[i-1] is part of the current solution
            j <- j-1
        else
            i <- i-1
        end
    end
    current <- current-1
end
</code>```

Walking through for the above example, we get the following solutions:

```<code>1) [5,3]
2) [3,3,2]
3) [2,2,2,2]
</code>```

Which is great! At least I thought, until I tried: {1,2} with a T=4. For this the table looks like:

```<code>1 0 0 0 0
1 1 1 1 1
1 1 2 2 3
</code>```

With the above algorithm to print all solutions, I only get:

```<code>[2,2]
[1,1,1,1]
</code>```

Which means I won't recover [2,1,1]. So this question is not about the generic how to print the solutions for different approaches to this problem, but how can I read the above DP table to find all solutions.

答:
Well I have one solution but sure... I can see why the other similar answers are using different approaches for this problem. So the algorithm to generate all the possible answers from the above table looks like:

```<code>private List<List<Integer>> readSolutions(int[] nums, int[][] dp, int currentRow, int currentColumn, List<Integer> partialSolution) {
    if (currentRow == 0) {
        return new ArrayList<>();
    }

    if (currentColumn == 0) {
        return new ArrayList<List<Integer>>(Collections.singleton(partialSolution));
    }

    List<List<Integer>> solutions = new ArrayList<>();
    if (dp[currentRow][currentColumn] != dp[currentRow-1][currentColumn]) {
        List<Integer> newSolution = new ArrayList<>(partialSolution);
        newSolution.add(nums[currentRow-1]);
        solutions.addAll(readSolutions(nums, dp, currentRow, currentColumn-nums[currentRow-1], newSolution));
        solutions.addAll(readSolutions(nums, dp, currentRow-1, currentColumn, partialSolution));

        return solutions;
    }

    return readSolutions(nums, dp, currentRow-1, currentColumn, partialSolution);
}
</code>```

The logic on the other hand is simple. Take the above table for example:

```<code>  0 1 2 3 4
0 1 0 0 0 0
1 1 1 1 1 1
2 1 1 2 2 3
</code>```

To get a single solution we start from the bottom right corner. If the value does match with the value directly above us, we move up. If it doesn't we move left by the amount corresponding to the row we're in. To generate all answers on on the other hand from the above table...

we're at some position (i,j)

if the value at (i-1,j) is the same as (i,j) we make a recursive call to (i-1,j)

if the values do not match, we have 2 choices...

we can use the number corresponding to the current row, and recurse into (i,j-n)

we can skip the number and check if we can create (i,j) instead by using a recursive call to (i-1,j) instead.

if we reach the first row, we return an empty list

if we reach the first column, we return what we have already found, which will have the sum of target.

Looks awful right, but works as expected.

Body:
I have seen different solutions to the same problem, but none of them seem to use the approach I used. So here I'm trying to solve the classical coin-change problem in a bottom up dynamic programming approach using a DP table.

    int[][] dp = new int[nums.length+1][target+1];
    for (int i = 0; i <= nums.length; ++i)
        dp[i][0] = 1;

    for (int i = 1; i < dp.length; ++i) {
        for (int j = 1; j < dp[i].length; ++j) {
            if (nums[i-1] <= j)
                dp[i][j] = dp[i-1][j] + dp[i][j-nums[i-1]];
            else
                dp[i][j] = dp[i-1][j];
        }
    }

The above code generates the table. For fun if I have: {2,3,5} coins, and want to exchange 8, the table would look like:

1 0 0 0 0 0 0 0 0
1 0 1 0 1 0 1 0 1
1 0 1 1 1 1 2 1 2
1 0 1 1 1 2 2 2 3

For the above the following method seem to be working well:

current <- 4
while (current > 0) do
    i <- current
    j <- 8
    while (j > 0) do
        if (dp[i][j] != dp[i-1][j]) then
            nums[i-1] is part of the current solution
            j <- j-1
        else
            i <- i-1
        end
    end
    current <- current-1
end

Walking through for the above example, we get the following solutions:

1) [5,3]
2) [3,3,2]
3) [2,2,2,2]

Which is great! At least I thought, until I tried: {1,2} with a T=4. For this the table looks like:

1 0 0 0 0
1 1 1 1 1
1 1 2 2 3

With the above algorithm to print all solutions, I only get:

[2,2]
[1,1,1,1]

Which means I won't recover [2,1,1]. So this question is not about the generic how to print the solutions for different approaches to this problem, but how can I read the above DP table to find all solutions.

Body:
Well I have one solution but sure... I can see why the other similar answers are using different approaches for this problem. So the algorithm to generate all the possible answers from the above table looks like:

private List<List<Integer>> readSolutions(int[] nums, int[][] dp, int currentRow, int currentColumn, List<Integer> partialSolution) {
    if (currentRow == 0) {
        return new ArrayList<>();
    }

    if (currentColumn == 0) {
        return new ArrayList<List<Integer>>(Collections.singleton(partialSolution));
    }

    List<List<Integer>> solutions = new ArrayList<>();
    if (dp[currentRow][currentColumn] != dp[currentRow-1][currentColumn]) {
        List<Integer> newSolution = new ArrayList<>(partialSolution);
        newSolution.add(nums[currentRow-1]);
        solutions.addAll(readSolutions(nums, dp, currentRow, currentColumn-nums[currentRow-1], newSolution));
        solutions.addAll(readSolutions(nums, dp, currentRow-1, currentColumn, partialSolution));

        return solutions;
    }

    return readSolutions(nums, dp, currentRow-1, currentColumn, partialSolution);
}

The logic on the other hand is simple. Take the above table for example:

  0 1 2 3 4
0 1 0 0 0 0
1 1 1 1 1 1
2 1 1 2 2 3

To get a single solution we start from the bottom right corner. If the value does match with the value directly above us, we move up. If it doesn't we move left by the amount corresponding to the row we're in. To generate all answers on on the other hand from the above table...

we're at some position (i,j)

if the value at (i-1,j) is the same as (i,j) we make a recursive call to (i-1,j)

if the values do not match, we have 2 choices...

we can use the number corresponding to the current row, and recurse into (i,j-n)

we can skip the number and check if we can create (i,j) instead by using a recursive call to (i-1,j) instead.

if we reach the first row, we return an empty list

if we reach the first column, we return what we have already found, which will have the sum of target.

Looks awful right, but works as expected.


问:
Why doesn't this JList update to show ArrayList attributes
I have below a method that should display attributes of arrayList elements in a list when called:

```<code>public void updateList(){

    DefaultListModel<String> model = (DefaultListModel<String>)jCustomerList.getModel();

        for(User user: theUserList.Users){
        model.addElement(user.getName());

        jCustomerList.setModel(model);

        }
}
</code>```

however when it is called the following error appears :

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: supermarketiteration2.ShopJFrame$63 cannot be cast to javax.swing.DefaultListModel

How do I resolve this?

EDIT**

The model has been made global as shown below, however now the error occurs when instantiating the model:

```<code>public class ShopJFrame extends javax.swing.JFrame {
private UserList theUserList;
private User currentCustomer;
private Customer castedCustomer;
private SupplierList theSupplierList;
private DeliveryCompanyList theDeliveryCompanyList;
private ProductList theProductList;
private Product selectedProduct;
private Supplier aSupplier;
private DeliveryCompany aDeliveryCompany;
//private JList jCustomerList;

private java.awt.Component jTabInMemory1;
private java.awt.Component jTabInMemory2;
private java.awt.Component jTabInMemory3;
private java.awt.Component jTabInMemory4;
private java.awt.Component jTabInMemory5;
private java.awt.Component jTabInMemory6;

DefaultListModel<String> model;

    public ShopJFrame() throws IOException, FileNotFoundException, ParseException {
        initComponents();
    theUserList = new UserList();
    User currentCustomer = new Customer();
    Customer castedCustomer = null;
    theDeliveryCompanyList = new DeliveryCompanyList();
    aDeliveryCompany = new DeliveryCompany();
    theSupplierList = new SupplierList();
    aSupplier = new Supplier();
    theProductList = new ProductList();

    jTabInMemory1 = jMainTabbedPane.getComponent(1);//PRODUCTS
    jMainTabbedPane.remove(1);
    jTabInMemory2 = jMainTabbedPane.getComponent(1);//REORDER
    jMainTabbedPane.remove(1);
    jTabInMemory3 = jMainTabbedPane.getComponent(1);//SUPPLY CHAIN
    jMainTabbedPane.remove(1);
    jTabInMemory4 = jMainTabbedPane.getComponent(1);//CATALOGUE
    jMainTabbedPane.remove(1);
    jTabInMemory5 = jMainTabbedPane.getComponent(1);//MY ACCOUNT
    jMainTabbedPane.remove(1);
    jTabInMemory6 = jMainTabbedPane.getComponent(1);//MY ACCOUNT
    jMainTabbedPane.remove(1);

    theProductList.loadFromFile(theProductList.getFilename());
    theSupplierList.loadFromFile();
    theDeliveryCompanyList.loadFromFile();
    theUserList.loadFromFile();
    theProductList.displayReorders(jProductReorderTextArea);

    this.updateComboBox("Supplier");
    this.updateComboBox("Delivery Company");
    this.updateComboBox("Products");
    model = (DefaultListModel<String>)jCustomerList.getModel();
    jCustomerList.setModel(model);
</code>```

答:
In swing a model is passed to the JComponent.

```<code>DefaultListModel<String> model = new DefaultListModel<>();
jCustomerList = new JList<String>(model);

model.addElement("Albert Einstein");
...
</code>```

_(The later JavaFX has observable data types, a bit more like binding as you intended.)_

Now one should neither create a new JList or ListModel.

```<code>public void updateList() {

    DefaultListModel<String> model = (DefaultListModel<>)jCustomerList.getModel();
    model.addElement("Madame Curie");
}
</code>```

Body:
I have below a method that should display attributes of arrayList elements in a list when called:

public void updateList(){

    DefaultListModel<String> model = (DefaultListModel<String>)jCustomerList.getModel();

        for(User user: theUserList.Users){
        model.addElement(user.getName());

        jCustomerList.setModel(model);

        }
}

however when it is called the following error appears :

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: supermarketiteration2.ShopJFrame$63 cannot be cast to javax.swing.DefaultListModel

How do I resolve this?

EDIT**

The model has been made global as shown below, however now the error occurs when instantiating the model:

public class ShopJFrame extends javax.swing.JFrame {
private UserList theUserList;
private User currentCustomer;
private Customer castedCustomer;
private SupplierList theSupplierList;
private DeliveryCompanyList theDeliveryCompanyList;
private ProductList theProductList;
private Product selectedProduct;
private Supplier aSupplier;
private DeliveryCompany aDeliveryCompany;
//private JList jCustomerList;

private java.awt.Component jTabInMemory1;
private java.awt.Component jTabInMemory2;
private java.awt.Component jTabInMemory3;
private java.awt.Component jTabInMemory4;
private java.awt.Component jTabInMemory5;
private java.awt.Component jTabInMemory6;

DefaultListModel<String> model;

    public ShopJFrame() throws IOException, FileNotFoundException, ParseException {
        initComponents();
    theUserList = new UserList();
    User currentCustomer = new Customer();
    Customer castedCustomer = null;
    theDeliveryCompanyList = new DeliveryCompanyList();
    aDeliveryCompany = new DeliveryCompany();
    theSupplierList = new SupplierList();
    aSupplier = new Supplier();
    theProductList = new ProductList();

    jTabInMemory1 = jMainTabbedPane.getComponent(1);//PRODUCTS
    jMainTabbedPane.remove(1);
    jTabInMemory2 = jMainTabbedPane.getComponent(1);//REORDER
    jMainTabbedPane.remove(1);
    jTabInMemory3 = jMainTabbedPane.getComponent(1);//SUPPLY CHAIN
    jMainTabbedPane.remove(1);
    jTabInMemory4 = jMainTabbedPane.getComponent(1);//CATALOGUE
    jMainTabbedPane.remove(1);
    jTabInMemory5 = jMainTabbedPane.getComponent(1);//MY ACCOUNT
    jMainTabbedPane.remove(1);
    jTabInMemory6 = jMainTabbedPane.getComponent(1);//MY ACCOUNT
    jMainTabbedPane.remove(1);

    theProductList.loadFromFile(theProductList.getFilename());
    theSupplierList.loadFromFile();
    theDeliveryCompanyList.loadFromFile();
    theUserList.loadFromFile();
    theProductList.displayReorders(jProductReorderTextArea);

    this.updateComboBox("Supplier");
    this.updateComboBox("Delivery Company");
    this.updateComboBox("Products");
    model = (DefaultListModel<String>)jCustomerList.getModel();
    jCustomerList.setModel(model);

Body:
In swing a model is passed to the JComponent.

DefaultListModel<String> model = new DefaultListModel<>();
jCustomerList = new JList<String>(model);

model.addElement("Albert Einstein");
...

_(The later JavaFX has observable data types, a bit more like binding as you intended.)_

Now one should neither create a new JList or ListModel.

public void updateList() {

    DefaultListModel<String> model = (DefaultListModel<>)jCustomerList.getModel();
    model.addElement("Madame Curie");
}


问:
Character encoding
For this piece of code:

```<code>String content = String.Empty;
ListenerStateObject state = (ListenerStateObject)ar.AsyncState;
Socket handler = state.workSocket;

int bytesRead = handler.EndReceive(ar);

if (bytesRead > 0)
{
   state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));

   content = state.sb.ToString();
   ...
</code>```

I'm geting 'Ol?' instead of 'Olá'

What's wrong with it?

答:
Most likely it's the wrong encoding.

But if you use this code to receive blocks of bytes (split by a protocol) you will have a serious flaw:  there is no guarantee that the block were independently encoded.

Simple case: the boundary of 2 blocks cuts through a multi-byte encoded char.

Best solution: Attach a TextReader to your Stream.

ContentLicense: CC BY-SA 3.0

Title: Character encoding

Body:
For this piece of code:

String content = String.Empty;
ListenerStateObject state = (ListenerStateObject)ar.AsyncState;
Socket handler = state.workSocket;

int bytesRead = handler.EndReceive(ar);

if (bytesRead > 0)
{
   state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));

   content = state.sb.ToString();
   ...

I'm geting 'Ol?' instead of 'Olá'

What's wrong with it?


问:
Nested cross validation for Lassocv
I'm new to Python and learning the ISLR book. in it I'm looking at the boston dataset and trying different models.
One of them is the LassoCV from sklearn.
I read here the importance of a nested loop and found the optimal lambda from the training data set.
See here the link
I'm trying to understand how I can use this specific lambda to see the MSE for the test data set.
Please help!
Here is my code:

```<code>##importing packages

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    from sklearn.linear_model import LinearRegression, LassoCV, RidgeCV
    import statsmodels.api as sm
    from sklearn.preprocessing import StandardScaler
    from sklearn.model_selection import cross_val_score, train_test_split
    from sklearn.datasets import load_boston
    bos = load_boston()

##creating the dataset

    boston = pd.DataFrame(bos.data)
    boston.columns = bos.feature_names

##defining X,y and spliting to train and test data

    y = boston['CRIM']
    X = boston.drop('CRIM',axis=1)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

##Lassocv first loop function
    lassocv =LassoCV(alphas=np.logspace(-5,-2.5,300),cv=5,normalize=True,max_iter=10000) #normalize functions as scale
    scaler = StandardScaler()
    lassocv.fit(X_train,y_train)
    mses = np.mean(lassocv.mse_path_,axis=1)
    alphas = lassocv.alphas_
    min_alpha = lassocv.alpha_
    min_mse = np.min(mses)
</code>```

Now that I have the right lambda, how do I incorporate it in to check the MSE for the test data?
Thanks!

答:
You can use the metrics from sklearn.

MSE metric

You can use the code:

```<code>from sklearn.metrics import mean_squared_error
y_pred = lassocv.predict(y_test)
print('MSE', mean_squared_error(y_test, y_pred)
</code>```

Title: Nested cross validation for Lassocv

Body:
I'm new to Python and learning the ISLR book. in it I'm looking at the boston dataset and trying different models.
One of them is the LassoCV from sklearn.
I read here the importance of a nested loop and found the optimal lambda from the training data set.
See here the link
I'm trying to understand how I can use this specific lambda to see the MSE for the test data set.
Please help!
Here is my code:

##importing packages

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    from sklearn.linear_model import LinearRegression, LassoCV, RidgeCV
    import statsmodels.api as sm
    from sklearn.preprocessing import StandardScaler
    from sklearn.model_selection import cross_val_score, train_test_split
    from sklearn.datasets import load_boston
    bos = load_boston()

##creating the dataset

    boston = pd.DataFrame(bos.data)
    boston.columns = bos.feature_names

##defining X,y and spliting to train and test data

    y = boston['CRIM']
    X = boston.drop('CRIM',axis=1)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

##Lassocv first loop function
    lassocv =LassoCV(alphas=np.logspace(-5,-2.5,300),cv=5,normalize=True,max_iter=10000) #normalize functions as scale
    scaler = StandardScaler()
    lassocv.fit(X_train,y_train)
    mses = np.mean(lassocv.mse_path_,axis=1)
    alphas = lassocv.alphas_
    min_alpha = lassocv.alpha_
    min_mse = np.min(mses)

Now that I have the right lambda, how do I incorporate it in to check the MSE for the test data?
Thanks!

Body:
You can use the metrics from sklearn.

MSE metric

You can use the code:

from sklearn.metrics import mean_squared_error
y_pred = lassocv.predict(y_test)
print('MSE', mean_squared_error(y_test, y_pred)


问:
PostgreSQL ERROR: canceling statement due to conflict with recovery
I'm getting the following error when running a query on a PostgreSQL db in standby mode. The query that causes the error works fine for 1 month but when you query for more than 1 month an error results.

```<code>ERROR: canceling statement due to conflict with recovery
Detail: User query might have needed to see row versions that must be removed
</code>```

Any suggestions on how to resolve? Thanks

答:
I'm going to add some updated info and references to @max-malysh's excellent answer above.

In short, if you do something on the master, it needs to be replicated on the slave. Postgres uses WAL records for this, which are sent after every logged action on the master to the slave. The slave then executes the action and the two are again in sync. In one of several scenarios, you can be in conflict on the slave with what's coming in from the master in a WAL action. In most of them, there's a transaction happening on the slave which conflicts with what the WAL action wants to change. In that case, you have two options:

Delay the application of the WAL action for a bit, allowing the slave to finish its conflicting transaction, then apply the action.

Cancel the conflicting query on the slave.

We're concerned with #1, and two values:

max_standby_archive_delay - this is the delay used after a long disconnection between the master and slave, when the data is being read from a WAL archive, which is not current data.

max_standby_streaming_delay - delay used for cancelling queries when WAL entries are received via streaming replication.

Generally, if your server is meant for high availability replication, you want to keep these numbers short. The default setting of 30000 (milliseconds if no units given) is sufficient for this. If, however, you want to set up something like an archive, reporting- or read-replica that might have very long-running queries, then you'll want to set this to something higher to avoid cancelled queries. The recommended 900s setting above seems like a good starting point. I disagree with the official docs on setting an infinite value -1 as being a good idea--that could mask some buggy code and cause lots of issues.

The one caveat about long-running queries and setting these values higher is that other queries running on the slave in parallel with the long-running one which is causing the WAL action to be delayed will see old data until the long query has completed. Developers will need to understand this and serialize queries which shouldn't run simultaneously.

For the full explanation of how max_standby_archive_delay and max_standby_streaming_delay work and why, go here.

Body:
I'm getting the following error when running a query on a PostgreSQL db in standby mode. The query that causes the error works fine for 1 month but when you query for more than 1 month an error results.

ERROR: canceling statement due to conflict with recovery
Detail: User query might have needed to see row versions that must be removed

Any suggestions on how to resolve? Thanks


问:
How to run sklearn.model_selection.GridSearchCV without splitting data?
I would like to evaluate the performance of a model pipeline.  I am not training my model on the ground-truth labels that I am evaluating the pipeline against, therefore doing a cross-validation scheme is unnecessary.  However, I would still like to use the grid search functionality provided in sklearn.

Is it possible to use sklearn.model_selection.GridSearchCV without splitting the data?  In other words, I would like to run Grid Search and get scores on the full dataset that I pass in to the pipeline.

Here is a simple example:

I might wish to choose the optimal k for KMeans.  I am actually going to be using KMeans on many datasets that are similar in some sense.  It so happens that I have some ground-truth labels for a few such datasets, which I will call my "training" data.  So, instead of using something like BIC, I decide to simply pick the optimal k for my training data, and employ that k for future datasets.  Search over possible values of k is a grid search.  KMeans is available in the sklearn library, so I can very easily define a grid search on this model.  Incidentally, KMeans takes in an "empty" y value, which simply passes through and can be used in a GridSearchCV scorer.  However, there is no sense in doing cross-validation here, since my individual kmeans models never see the ground truth labels and are therefore incapable of overfitting.

To be clear, the above example is simply a contrived example to justify a possible use case for such a thing for those who are afraid that I might abuse this functionality.  The solution to the example above that I am interested in is how to not split the data in GridSearchCV.

Is it possible to use sklearn.model_selection.GridSearchCV without splitting the data?

答: You need to do cross-validation if you do grid search, otherwise you will overfit on the test data, because you evaluate several settings of hyper-parameters on the same data.</p>


问:
Nth max salary in Oracle
To find out the Nth max sal in oracle i'm using below query

```<code>SELECT DISTINCE sal
FROM emp a
WHERE (
       SELECT COUNT(DISTINCE sal)
       FROM emp b
       WHERE a.sal<=b.sal)=&n;
</code>```

But According to me by using the above query it will take more time to execute if table size is big.

i'm trying to use the below query

```<code>SELECT sal
FROM (
      SELECT DISTINCE sal
      FROM emp
           ORDER BY sal DESC )
WHERE rownum=3;
</code>```

but not getting output.. any suggetions please .. Please share any link on how to optimise queries and decrease the time for a query to execute.

答:
```<code>select * from (select rownum as rownumber,emp1.* from (select * from emp order by sal desc) emp1) where rownumber = 3;
</code>```

Title: Nth max salary in Oracle

Body:
To find out the Nth max sal in oracle i'm using below query

SELECT DISTINCE sal
FROM emp a
WHERE (
       SELECT COUNT(DISTINCE sal)
       FROM emp b
       WHERE a.sal<=b.sal)=&n;

But According to me by using the above query it will take more time to execute if table size is big.

i'm trying to use the below query

SELECT sal
FROM (
      SELECT DISTINCE sal
      FROM emp
           ORDER BY sal DESC )
WHERE rownum=3;

but not getting output.. any suggetions please .. Please share any link on how to optimise queries and decrease the time for a query to execute.


问:
Testing loading spinner selenium
I'm trying to automate a test case about a loading spinner which is displayed when navigating between the different page categories while the page is loading.

The spinner has two states:
When is not visible - "display: none;"

Visible state while the page is loading - "display: block;"

The problem is when navigate between the different categories I'm using a method

selectCategory("Gallery");

and then not sure how to assert that the spinner is visible while the page is being load.
It's like webdriver is looking for the spinner when it's already gone and the category is load.

答:
This is what I am using in NodeJS and TypeScript to wait for all spinners.  It checks the alt text and src text attributes.</p>

```<code>public async WaitForAllSpinners(): Promise<void> {
    const elements = await this.driver.findElements(By.css("img"));
    const keywords = ["loading", "loader", "spinner"];

    for (const element of elements) {
        let altText = "";
        let srcText = "";

        //Element may be stale by the time we check it
        try {
            altText = await element.getAttribute("alt");
        } catch (error) {}

        //Element may be stale by the time we check it
        try {
            srcText = await element.getAttribute("src");
        } catch (error) {}

        let identifiedByAltText = false;
        let identifiedBySrcText = false;

        for (const keyword of keywords) {
            if (altText && altText.toLowerCase().indexOf(keyword) >= 0) {
                identifiedByAltText = true;
                break;
            }
            if (srcText && srcText.toLocaleLowerCase().indexOf(keyword) >= 0) {
                identifiedBySrcText = true;
                break;
            }
        }

        if (identifiedByAltText || identifiedBySrcText) {
            //Element may be stale by the time we wait for it
            try {
                await this.driver.wait(until.elementIsNotVisible(element), this._testConfig.DefaultElementTimeout);
            } catch (error) {}
        }
    }
}
</code>```

Title: Testing loading spinner selenium

Body:
This is what I am using in NodeJS and TypeScript to wait for all spinners.  It checks the alt text and src text attributes.

public async WaitForAllSpinners(): Promise<void> {
    const elements = await this.driver.findElements(By.css("img"));
    const keywords = ["loading", "loader", "spinner"];

    for (const element of elements) {
        let altText = "";
        let srcText = "";

        //Element may be stale by the time we check it
        try {
            altText = await element.getAttribute("alt");
        } catch (error) {}

        //Element may be stale by the time we check it
        try {
            srcText = await element.getAttribute("src");
        } catch (error) {}

        let identifiedByAltText = false;
        let identifiedBySrcText = false;

        for (const keyword of keywords) {
            if (altText && altText.toLowerCase().indexOf(keyword) >= 0) {
                identifiedByAltText = true;
                break;
            }
            if (srcText && srcText.toLocaleLowerCase().indexOf(keyword) >= 0) {
                identifiedBySrcText = true;
                break;
            }
        }

        if (identifiedByAltText || identifiedBySrcText) {
            //Element may be stale by the time we wait for it
            try {
                await this.driver.wait(until.elementIsNotVisible(element), this._testConfig.DefaultElementTimeout);
            } catch (error) {}
        }
    }
}


问:
How to make text boxes appear using jQuery
I am trying to make the corresponding textarea appear when Abnormal is clicked and disappear when Normal is clicked. The problem I am having is that when I click Abnormal for one question it affects both textareas and not the one it corresponds to.

$("[nfield='horizontal_field']").on("change", function() {
  $("[mrbvalue='Normal']").on('change', function() {
    if ($("[mrbvalue='Normal']:checked")) {
      $('[nfield="txt_fieldhori"]').show()
    }
  });

  $("[mrbvalue='Abnormal']").on('change', function() {
    if ($("[mrbvalue='Abnormal']:checked")) {
      $('[nfield="txt_fieldhori"]').hide()
    }
  });
})

$("[nfield='vert_field']").on('change', function() {
  $("[mrbvalue='Normal']").on('change', function() {
    if ($("[mrbvalue='Normal']:checked")) {
      $('[nfield="txt_nooo"]').show()
    }
  });

  $("[mrbvalue='Abnormal']").on('change', function() {
    if ($("[mrbvalue='Abnormal']:checked")) {
      $('[nfield="txt_nooo"]').hide()
    }
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="n-mrb n-choice q" nfield="horizontal_field">
  <div class="mrb-item"><label><input type="radio" name="horizontal_field" mrbvalue="Normal" class="k-valid"> Normal</label></div>
  <div class="mrb-item"><label><input type="radio" name="horizontal_field" mrbvalue="Abnormal" class="k-valid"> Abnormal</label></div>
</div>
<textarea class="n-text comment -EntireLine ee k-valid" nfield="txt_fieldhori" id="tet"></textarea>
<div class="n-mrb n-choice q" nfield="vert_field">
  <div class="mrb-item"><label><input type="radio" name="vert_field" mrbvalue="Normal" class="k-valid"> Normal</label></div>
  <div class="mrb-item"><label><input type="radio" name="vert_field" mrbvalue="Abnormal" class="k-valid"> Abnormal</label></div>
</div>
<textarea class="n-text comment -EntireLine ee k-valid" nfield="txt_nooo" id="te"></textarea></code>```

答:
You are overcomplicating it and selecting all corresponding items instead the one you are interested about. Let's have a simpler, correct solution along with explanation:

```<code>var textAreas = document.querySelectorAll("textarea.n-text.comment");
var radioButtons = document.querySelectorAll("input[type=radio]");
for (let index = 0; index < radioButtons.length; index++) {
    radioButtons[index].addEventListener("change", function() {
      textAreas[(index - (index % 2)) / 2].style.display = (index % 2) ? "none" : "block";
  });
}
</code>```

What happens:

we load all text areas into an array-like object

we load all radio buttons into an array-like object

we loop through the set of radio buttons, using the let keyword to acquire block context for the index

we add a change event for the current radio button

(index - (index % 2)) / 2 yields the correct text area index from the radio button index

each pair radio button should hide the text area and each odd should show

we change the display accordingly

Body:
I am trying to make the corresponding textarea appear when Abnormal is clicked and disappear when Normal is clicked. The problem I am having is that when I click Abnormal for one question it affects both textareas and not the one it corresponds to.

$("[nfield='horizontal_field']").on("change", function() {
  $("[mrbvalue='Normal']").on('change', function() {
    if ($("[mrbvalue='Normal']:checked")) {
      $('[nfield="txt_fieldhori"]').show()
    }
  });

  $("[mrbvalue='Abnormal']").on('change', function() {
    if ($("[mrbvalue='Abnormal']:checked")) {
      $('[nfield="txt_fieldhori"]').hide()
    }
  });
})

$("[nfield='vert_field']").on('change', function() {
  $("[mrbvalue='Normal']").on('change', function() {
    if ($("[mrbvalue='Normal']:checked")) {
      $('[nfield="txt_nooo"]').show()
    }
  });

  $("[mrbvalue='Abnormal']").on('change', function() {
    if ($("[mrbvalue='Abnormal']:checked")) {
      $('[nfield="txt_nooo"]').hide()
    }
  })
});

<input type="radio" name="horizontal_field" mrbvalue="Normal" class="k-valid"> Normal

<input type="radio" name="horizontal_field" mrbvalue="Abnormal" class="k-valid"> Abnormal

<textarea class="n-text comment -EntireLine ee k-valid" nfield="txt_fieldhori" id="tet"></textarea>

<input type="radio" name="vert_field" mrbvalue="Normal" class="k-valid"> Normal

<input type="radio" name="vert_field" mrbvalue="Abnormal" class="k-valid"> Abnormal

<textarea class="n-text comment -EntireLine ee k-valid" nfield="txt_nooo" id="te"></textarea>

Body:
You are overcomplicating it and selecting all corresponding items instead the one you are interested about. Let's have a simpler, correct solution along with explanation:

var textAreas = document.querySelectorAll("textarea.n-text.comment");
var radioButtons = document.querySelectorAll("input[type=radio]");
for (let index = 0; index < radioButtons.length; index++) {
    radioButtons[index].addEventListener("change", function() {
      textAreas[(index - (index % 2)) / 2].style.display = (index % 2) ? "none" : "block";
  });
}

What happens:

we load all text areas into an array-like object

we load all radio buttons into an array-like object

we loop through the set of radio buttons, using the let keyword to acquire block context for the index

we add a change event for the current radio button

(index - (index % 2)) / 2 yields the correct text area index from the radio button index

each pair radio button should hide the text area and each odd should show

we change the display accordingly


问:
How to decode a JSON string?
On the server side do I have 2 hashes I encode into JSON strings like so

```<code>my $j = JSON->new;
$j = $j->utf8;

my $data;
$data->{users}  = $j->encode(\%user_result);
$data->{owners} = $j->encode(\%owner_result);
$json_string    = to_json($data);

print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json_string;
</code>```

On the client side I have

```<code>$(document).ready(function(){

    $('form').live('submit', function(){

    $.ajax({
        type: "GET",
        url: "/cgi-bin/ajax_confirm.pl",
        contentType: "application/json; charset=utf-8",
        dataType: "json",

        data: $(this).serialize(),

        error: function(XMLHttpRequest, textStatus, errorThrown) {
        $('div#create_result').text("responseText: " + XMLHttpRequest.responseText +
                        ", textStatus: " + textStatus +
                        ", errorThrown: " + errorThrown);
        $('div#create_result').addClass("error");
        },

        success: function(result){
        if (result.error) {
            $('div#create_result').text("result.error: " + result.error);
            $('div#create_result').addClass("error");
        } else { // perl script says everything is okay

            var users  = result.users;
            var owners = result.owners;
...
</code>```

users contains

```<code>{"ss":"Sandra Schlichting","fn":"Full name"}
</code>```

but it is not an array. When I use $.each() it takes on character at a time.

Problem

How do I turn it into an array, so I can use

```<code>function makeTable(users) {
    var result = '<table>\n<tr><td>Initials</td><td>Full Name</td></tr>\n';
    $.each(users, function(index, value) {
        result += '<tr><td>' + index + '</td><td>' + value + '</td></tr>\n';
    });
    result += '</table>';
    return (result);
}
</code>```

which should produce

```<code>Initials    Full Name
ss  Sandra Schlichting
fn  Full name
</code>```

答:
You can use the JSON parser created by douglas crockford:

https://github.com/douglascrockford/JSON-js

include the json2.js in your page, the you can do:

```<code>var object = JSON.parse(string);
</code>```

Then you can use it as an array.

Title: How to decode a JSON string?

Body:
On the server side do I have 2 hashes I encode into JSON strings like so

my $j = JSON->new;
$j = $j->utf8;

my $data;
$data->{users}  = $j->encode(\%user_result);
$data->{owners} = $j->encode(\%owner_result);
$json_string    = to_json($data);

print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json_string;

On the client side I have

$(document).ready(function(){

    $('form').live('submit', function(){

    $.ajax({
        type: "GET",
        url: "/cgi-bin/ajax_confirm.pl",
        contentType: "application/json; charset=utf-8",
        dataType: "json",

        data: $(this).serialize(),

        error: function(XMLHttpRequest, textStatus, errorThrown) {
        $('div#create_result').text("responseText: " + XMLHttpRequest.responseText +
                        ", textStatus: " + textStatus +
                        ", errorThrown: " + errorThrown);
        $('div#create_result').addClass("error");
        },

        success: function(result){
        if (result.error) {
            $('div#create_result').text("result.error: " + result.error);
            $('div#create_result').addClass("error");
        } else { // perl script says everything is okay

            var users  = result.users;
            var owners = result.owners;
...

users contains

{"ss":"Sandra Schlichting","fn":"Full name"}

but it is not an array. When I use $.each() it takes on character at a time.

Problem

How do I turn it into an array, so I can use

function makeTable(users) {
    var result = '
\n
Initials	Full Name
\n';
    $.each(users, function(index, value) {
        result += '
' + index + '	' + value + '
\n';
    });
    result += '
';
    return (result);
}

which should produce

Initials    Full Name
ss  Sandra Schlichting
fn  Full name

Body:
You can use the JSON parser created by douglas crockford:

https://github.com/douglascrockford/JSON-js

include the json2.js in your page, the you can do:

var object = JSON.parse(string);

Then you can use it as an array.


问:
How could avoid these terminal errors for ionic installation?
I formatted my computer because I had accidentally installed ionic with sudo. Now, I installed Catalina from the beginning and installed Node.js again. Although, I still face a problem installing ionic. </p>

答:
Are you using a node version manager like NVM: https://github.com/nvm-sh/nvm?

Otherwise, NPM has details on how to resolve the EACCES error:
https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally


问:
From array, generate all distinct, non-empty subarrays, with preserved order
I have an array, with subarrays and need an algorithm that generates all possible distinct combinations of the subarrays. The resultant combinations can be any length. For example, if the Array has 4 subarrays, the first subarray by itself would be a unique and valid resultant combination, as would any other unique combination of any length.

A combination with the sub-array with the same items in a different order would not be considered unique.

let mainArray = [[0.3, 1], [0.5, 2], [0.6, 3], [0.3, 4]]

// Valid resultant combinations:
[[0.3, 1]]
[[0.3, 1], [0.5, 2]]
[[0.3, 1], [0.5, 2], [0.6, 3]]
[[0.3, 1], [0.5, 2], [0.6, 3], [0.3, 4]]
[[0.5, 2]]
[[0.5, 2], [0.6, 3]]
[[0.5, 2], [0.6, 3], [0.3, 4]]
[[0.6, 3]]
[[0.6, 3], [0.3, 4]]
[[0.3, 4]]
[[0.3, 1], [0.6, 3], [0.3, 4]]
[[0.3, 1], [0.5, 2], [0.3, 4]]
[[0.3, 1], [0.3, 4]]
[[0.3, 1], [0.6, 3]]
[[0.5, 2], [0.3, 4]]

// Don’t think I missed any.
```

答:
For a more convenient handling, you could take an array of indices and write the code for getting all combinations.

Later, you could replace the array with indices by the real values.

This approach works with a recusion which keeps an array of collected items and an index, which points to the handed over array.

At start, you have a standard exit condition of a recusion which checks if the index is greater than possible and adds the collected values to the result set.

The following part calls the function again with the peviously collected value and a new value from the array and an incremented index and with aother call with only a changed index (here, the actual item is not used).

function getCombinations(array) {
    function iter(temp, index) {
        if (index >= array.length) {
            result.push(temp);
            return;
        }

        iter([...temp, array[index]], index + 1);
        iter(temp, index + 1);
    }

    var result = [];
    iter([], 0);
    return result;
}

let array = [[0.3, 1], [0.5, 2], [0.6, 3], [0.3, 4]];

console.log('indices')
getCombinations([...array.keys()]).forEach(a => console.log(...a));
console.log('arrays')
getCombinations(array).forEach(a => console.log(...a.map(b => JSON.stringify(b))));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
For a more convenient handling, you could take an array of indices and write the code for getting all combinations.

Later, you could replace the array with indices by the real values.

This approach works with a recusion which keeps an array of collected items and an index, which points to the handed over array.

At start, you have a standard exit condition of a recusion which checks if the index is greater than possible and adds the collected values to the result set.

The following part calls the function again with the peviously collected value and a new value from the array and an incremented index and with aother call with only a changed index (here, the actual item is not used).

function getCombinations(array) {
    function iter(temp, index) {
        if (index >= array.length) {
            result.push(temp);
            return;
        }

        iter([...temp, array[index]], index + 1);
        iter(temp, index + 1);
    }

    var result = [];
    iter([], 0);
    return result;
}

let array = [[0.3, 1], [0.5, 2], [0.6, 3], [0.3, 4]];

console.log('indices')
getCombinations([...array.keys()]).forEach(a => console.log(...a));
console.log('arrays')
getCombinations(array).forEach(a => console.log(...a.map(b => JSON.stringify(b))));

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


问:
Cannot assign "3": "StudentsEnrolledSubject.Subject_Section_Teacher" must be a "SubjectSectionTeacher" instance
Django signal Cannot assign "3": "StudentsEnrolledSubject.Subject_Section_Teacher" must be a "SubjectSectionTeacher" instance. i have foreignkey Subject_Section_Teacher in StudentsEnrolledSubject related in SubjectSectionTeacher

in this line  Subject_Section_Teacher=each.Employee_Users.id is my error

I have this models.py

```<code>class StudentsEnrolledSubject(models.Model):
    Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,null=True)
    Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE,null=True)
    @receiver(pre_save, sender=StudentsEnrollmentRecord)
    def get_older_instance(sender, instance, *args, **kwargs):
        try:
            instance._old_instance = StudentsEnrollmentRecord.objects.get(pk=instance.pk)
        except StudentsEnrollmentRecord.DoesNotExist:
            instance._old_instance = None

    @receiver(post_save, sender=StudentsEnrollmentRecord)
    def create(sender, instance, created, *args, **kwargs):
        if not created:
            older_instance = instance._old_instance
            if older_instance.Courses != instance.Courses or \
                    older_instance.Section != instance.Section or \
                    older_instance.Education_Levels != instance.Education_Levels:

                StudentsEnrolledSubject.objects.filter(
                    Students_Enrollment_Records=instance
                ).delete()
            else:
                return None

        teachers = SubjectSectionTeacher.objects.filter(Sections=instance.Section,
                                                        Education_Levels=instance.Education_Levels,
                                                        Courses=instance.Courses)
        for each in teachers:
            StudentsEnrolledSubject.objects.create(
                Students_Enrollment_Records=instance,
                Subject_Section_Teacher=each.Employee_Users.id)

class SubjectSectionTeacher(models.Model):
    School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE,null=True)
    Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True)
    Courses= models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,null=True,blank=True)
    Sections= models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE,null=True)
    Subjects= models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE,null=True)
    Employee_Users= models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE,null=True)
</code>```

答:
As the error message states, you are trying to assign an integer (the teacher's user id) to a field that should be a SubjectSectionTeacher instance. All you ned to do is leave off the .Employee_Users.id, and you'll solve this error. I'm also going to modify your each variable to be teacher to make it more clear.

# ...
        for teacher in teachers:
            StudentsEnrolledSubject.objects.create(
                Students_Enrollment_Records=instance,
                Subject_Section_Teacher=teacher)
```

Body:
Django signal Cannot assign "3": "StudentsEnrolledSubject.Subject_Section_Teacher" must be a "SubjectSectionTeacher" instance. i have foreignkey Subject_Section_Teacher in StudentsEnrolledSubject related in SubjectSectionTeacher

in this line  Subject_Section_Teacher=each.Employee_Users.id is my error

I have this models.py

class StudentsEnrolledSubject(models.Model):
    Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,null=True)
    Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE,null=True)
    @receiver(pre_save, sender=StudentsEnrollmentRecord)
    def get_older_instance(sender, instance, *args, **kwargs):
        try:
            instance._old_instance = StudentsEnrollmentRecord.objects.get(pk=instance.pk)
        except StudentsEnrollmentRecord.DoesNotExist:
            instance._old_instance = None

    @receiver(post_save, sender=StudentsEnrollmentRecord)
    def create(sender, instance, created, *args, **kwargs):
        if not created:
            older_instance = instance._old_instance
            if older_instance.Courses != instance.Courses or \
                    older_instance.Section != instance.Section or \
                    older_instance.Education_Levels != instance.Education_Levels:

                StudentsEnrolledSubject.objects.filter(
                    Students_Enrollment_Records=instance
                ).delete()
            else:
                return None

        teachers = SubjectSectionTeacher.objects.filter(Sections=instance.Section,
                                                        Education_Levels=instance.Education_Levels,
                                                        Courses=instance.Courses)
        for each in teachers:
            StudentsEnrolledSubject.objects.create(
                Students_Enrollment_Records=instance,
                Subject_Section_Teacher=each.Employee_Users.id)

class SubjectSectionTeacher(models.Model):
    School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE,null=True)
    Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True)
    Courses= models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,null=True,blank=True)
    Sections= models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE,null=True)
    Subjects= models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE,null=True)
    Employee_Users= models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE,null=True)


问:
RoR: collection_select not setting the value in the DB
I am using Rails 3 and I am having a problem. My collection_select is not populating the field in the DB. This is what my view looks like: (some html was removed)

```<code>f.label "Company Name"
@c = Company.all
collection_select(:Company , :company_id, @c, :id , :companyName, {:prompt => true})
f.submit
</code>```

The drop down list has the correct values, but when I submit it, this is what my params looks like: "Company"=>{"company_id"=>"2"}. I don't have a field called company, but I do have a field called company_id and a table called company. Is my syntax correct?

```<code>Processing by RecordsController#create as HTML

Parameters: {"utf8"=>"âœ“", "authenticity_token"=>"WLzwCoZFCUhyH9ZqYWYLmaQwyleB3JLoTnb4lhftKzc=", "record"=>{"title"=>"test", "Company"=>{"company_id"=>"2"}, "commit"=>"Create record"}

AREL (2.0ms)  INSERT INTO "records" ("company_id", "title", "created_at", "updated_at") VALUES (NULL, 'test','2011-05-17 05:01:38.905717', '2011-05-17 05:01:38.905717')
Redirected to http://localhost:3000/Records/7
Completed 302 Found in 150ms
</code>```

答:
Try this

```<code># in controller
@companies = Company.all

collection_select @record, :company_id, @companies, :id, :companyName
</code>```

or

```<code>form_for @record do |f|
  = f.collection_select :company_id, @companies, :id, :companyName
</code>```

Body:
I am using Rails 3 and I am having a problem. My collection_select is not populating the field in the DB. This is what my view looks like: (some html was removed)

f.label "Company Name"
@c = Company.all
collection_select(:Company , :company_id, @c, :id , :companyName, {:prompt => true})
f.submit

The drop down list has the correct values, but when I submit it, this is what my params looks like: "Company"=>{"company_id"=>"2"}. I don't have a field called company, but I do have a field called company_id and a table called company. Is my syntax correct?

Processing by RecordsController#create as HTML

Parameters: {"utf8"=>"âœ“", "authenticity_token"=>"WLzwCoZFCUhyH9ZqYWYLmaQwyleB3JLoTnb4lhftKzc=", "record"=>{"title"=>"test", "Company"=>{"company_id"=>"2"}, "commit"=>"Create record"}

AREL (2.0ms)  INSERT INTO "records" ("company_id", "title", "created_at", "updated_at") VALUES (NULL, 'test','2011-05-17 05:01:38.905717', '2011-05-17 05:01:38.905717')
Redirected to http://localhost:3000/Records/7
Completed 302 Found in 150ms

Body:
Try this

# in controller
@companies = Company.all

collection_select @record, :company_id, @companies, :id, :companyName

or

form_for @record do |f|
  = f.collection_select :company_id, @companies, :id, :companyName


问:
SSRS SQL closest future date to current date
I have a table of securities (added spaces for better readability) with coupon payment dates (if it's a bond) and I need to make a table where for every client and security he owns, there is a column with only next coupon payment. If its a share, it will  be in the table but with no payment.
So from column coupon payment date, I need to select only the next coupon payment date.

from this(let's call it table 'Coupons':

    ClientName I SecID I  SecType I   CouponPaymentdate

    Client1 I US00001 I Bond I 06/2017

    Client1 I US00001 I Bond I 06/2018

Client1 I US00001 I Bond I 06/2019

Client1 I US00001 I Bond I 06/2020

Client1 I US00001 I Bond I 06/2021

Client1 I US00002 I Bond I 03/2019

Client1 I US00002 I Bond I 03/2020

Client1 I US00002 I Bond I 03/2021

Client2 I US00003 I Share I -

Client3 I US00004 I Bond I 01/2017

Client3 I US00004 I Bond I 01/2018

desired result

ClientName I SecID I SecType I NextCouponPaymentdate

Client1 I US00001 I Bond I 06/2020

Client1 I US00002 I Bond I 03/2020

Client2 I US00003 I Share I -

for this column I tried this, but I need to break ClientName and SecID

   (SELECT TOP 1 Coupons.CouponPaymentDate FROM Coupons as CPN
   WHERE CPN.CouponPaymentDate > GETDATE()
   ORDER BY CPN.CouponPaymentDate)

Any advice? I use SSRS, so maybe even an expression for this would be helpful but I have no idea. Thank you (Sorry for formatting)

答:
edit: see Alan's solution. Seems to return same results with less code.

My approach for this is to create an additional column to calculate the difference between the payment date and use the row number function to determine the record closest to current day.

I created a temp table to insert the values you provided (I replaced "-" with null in the couponpaymentdate column for SecType = "Share") to test the result

```<code>CREATE TABLE #yourtable (
ClientName nvarchar(50),
SecID nvarchar(50),
SecType nvarchar(50),
CouponPaymentDate datetime)

INSERT INTO #yourtable VALUES
('Client1', 'US00001', 'Bond' , '06/01/2017'),
('Client1', 'US00001', 'Bond' , '06/01/2018'),
('Client1', 'US00001', 'Bond' , '06/01/2019'),
('Client1', 'US00001', 'Bond' , '06/01/2020'),
('Client1', 'US00001', 'Bond' , '06/01/2021'),
('Client1', 'US00002', 'Bond' , '03/01/2019'),
('Client1', 'US00002', 'Bond' , '03/01/2020'),
('Client1', 'US00002', 'Bond' , '03/01/2021'),
('Client2', 'US00003', 'Share', null),
('Client3', 'US00004', 'Bond' , '01/01/2017'),
('Client3', 'US00004', 'Bond' , '01/01/2018');
</code>```

calculated difference in days in column aliased "duration_days" and include only future days/nulls

```<code>select
ClientName,
SecID,
SecType,
CouponPaymentDate,
MIN(ABS(DATEDIFF(d,GETDATE(),CouponPaymentDate))) as duration_days
into #yourtable2
from #yourtable
WHERE (CouponPaymentDate > GETDATE() OR CouponPaymentDate is null)
group by ClientName,SecID,SecType,CouponPaymentDate
</code>```

rn represents row number and since the rows are ordered by ascending duration_days, rn = 1 will be the date closest to current day. This will also provide you with the future date if the current day is right between two couponpaymentdates.

```<code>SELECT ClientName,SecID,SecType,CouponPaymentDate
FROM
(select
ROW_NUMBER() OVER (partition by SecID order by duration_days, CouponPaymentDate desc) rn,
ClientName,
SecID,
SecType,
CouponPaymentDate,
duration_days
from #yourtable2
) table_alias
where rn = 1
</code>```

**Replace #yourtable with Coupons

Body:
edit: see Alan's solution. Seems to return same results with less code.

My approach for this is to create an additional column to calculate the difference between the payment date and use the row number function to determine the record closest to current day.

I created a temp table to insert the values you provided (I replaced "-" with null in the couponpaymentdate column for SecType = "Share") to test the result

CREATE TABLE #yourtable (
ClientName nvarchar(50),
SecID nvarchar(50),
SecType nvarchar(50),
CouponPaymentDate datetime)

INSERT INTO #yourtable VALUES
('Client1', 'US00001', 'Bond' , '06/01/2017'),
('Client1', 'US00001', 'Bond' , '06/01/2018'),
('Client1', 'US00001', 'Bond' , '06/01/2019'),
('Client1', 'US00001', 'Bond' , '06/01/2020'),
('Client1', 'US00001', 'Bond' , '06/01/2021'),
('Client1', 'US00002', 'Bond' , '03/01/2019'),
('Client1', 'US00002', 'Bond' , '03/01/2020'),
('Client1', 'US00002', 'Bond' , '03/01/2021'),
('Client2', 'US00003', 'Share', null),
('Client3', 'US00004', 'Bond' , '01/01/2017'),
('Client3', 'US00004', 'Bond' , '01/01/2018');

calculated difference in days in column aliased "duration_days" and include only future days/nulls

select
ClientName,
SecID,
SecType,
CouponPaymentDate,
MIN(ABS(DATEDIFF(d,GETDATE(),CouponPaymentDate))) as duration_days
into #yourtable2
from #yourtable
WHERE (CouponPaymentDate > GETDATE() OR CouponPaymentDate is null)
group by ClientName,SecID,SecType,CouponPaymentDate

rn represents row number and since the rows are ordered by ascending duration_days, rn = 1 will be the date closest to current day. This will also provide you with the future date if the current day is right between two couponpaymentdates.

SELECT ClientName,SecID,SecType,CouponPaymentDate
FROM
(select
ROW_NUMBER() OVER (partition by SecID order by duration_days, CouponPaymentDate desc) rn,
ClientName,
SecID,
SecType,
CouponPaymentDate,
duration_days
from #yourtable2
) table_alias
where rn = 1

**Replace #yourtable with Coupons


问:
Couldn't match type ‘PersistEntityBackend U’ with ‘SqlBackend’
The following code produces a compile error Couldn't match type ‘PersistEntityBackend U’ with ‘SqlBackend’ arising from a use of ‘insertUser’ due to the commented line:

```<code>sampleUser :: Entity User
sampleUser = Entity (toSqlKey 1) $ User
  { userName = "admin"
  , userEmail = "admin@test.com"
  }

type U = Entity User

connectInfo :: MySQLConnectInfo
connectInfo = undefined

runAction :: (MonadUnliftIO m, IsPersistBackend r, BaseBackend r ~ SqlBackend) => MySQLConnectInfo -> ReaderT r (LoggingT m) a -> m a
runAction connectInfo action = runStdoutLoggingT $ withMySQLConn connectInfo $ \backend ->
  runReaderT action backend

insertUser :: (PersistEntity U, PersistRecordBackend U SqlBackend) =>
             U -> ReaderT SqlBackend (LoggingT IO) (Key U)
insertUser = insert

doDBStuff :: IO ()
doDBStuff = do
  runAction connectInfo (runMigration migrateAll)
  runAction connectInfo (insertUser sampleUser) -- compile error
  return ()
</code>```

As far as I can see, I've specialized all the types in insertUser and have added all necessary constraints (having read the related SO question). What am I missing?

答:
You have a PersistRecordBackend U SqlBackend constraint I don't know if you need, but I suspect you need a PersistEntityBackend U ~ SqlBackend constraint for insertUser. Or so the compiler suggests.

See Couldn't match type ‘PersistEntityBackend (Entity a)’ with ‘SqlBackend’

Body:
The following code produces a compile error Couldn't match type ‘PersistEntityBackend U’ with ‘SqlBackend’ arising from a use of ‘insertUser’ due to the commented line:

sampleUser :: Entity User
sampleUser = Entity (toSqlKey 1) $ User
  { userName = "admin"
  , userEmail = "admin@test.com"
  }

type U = Entity User

connectInfo :: MySQLConnectInfo
connectInfo = undefined

runAction :: (MonadUnliftIO m, IsPersistBackend r, BaseBackend r ~ SqlBackend) => MySQLConnectInfo -> ReaderT r (LoggingT m) a -> m a
runAction connectInfo action = runStdoutLoggingT $ withMySQLConn connectInfo $ \backend ->
  runReaderT action backend

insertUser :: (PersistEntity U, PersistRecordBackend U SqlBackend) =>
             U -> ReaderT SqlBackend (LoggingT IO) (Key U)
insertUser = insert

doDBStuff :: IO ()
doDBStuff = do
  runAction connectInfo (runMigration migrateAll)
  runAction connectInfo (insertUser sampleUser) -- compile error
  return ()

As far as I can see, I've specialized all the types in insertUser and have added all necessary constraints (having read the related SO question). What am I missing?


问:
What is the correctly way to delete edges with orientdb OGM in django rest framework?
I don't know how to create a method to delete edges in django rest framework, using orientdb OGM.

I'm using pyorient==1.5.5 and OrientDB 3.0.18 version.

I have two vertex Classes: ousers, ocompany. Also I have two relationships (edges) Classes: ofriends, oworksat. So for example:

To make a ofriends relationship, I need two ousers.
And to make a oworksat relationship, I need one ouser and one ocompany.
Every relationship has it own cluster id.

I know that I can access to these functions:

```<code>(Pdb) dir(graph)
</code>```

['PROPERTY_TYPES', '_GROOVY_GET_DB', '_GROOVY_NULL_LISTENER', '_GROOVY_TRY', 'class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref', '_last_cred', '_last_db', '_last_user', 'batch', 'both', 'bothE', 'build_mapping', 'clear_registry', 'client', 'coerce_class_names', 'coerce_class_names_to_quoted', 'compute_all_properties', 'config', 'create_all', 'create_class', 'create_edge', 'create_edge_command', 'create_function', 'create_props_mapping', 'create_vertex', 'create_vertex_command', 'delete_vertex', 'delete_vertex_command', 'drop', 'drop_all', 'drop_class', 'edge_from_record', 'edges_from_records', 'element_from_link', 'element_from_record', 'elements_from_links', 'elements_from_records', 'export', 'get_edge', 'get_element', 'get_vertex', 'gremlin', 'guard_reserved_words', 'inE', 'in_', 'include', 'init_broker_for_class', 'list_superclasses', 'ocompany', 'ofriends', 'open', 'ousers', 'out', 'outE', 'oworksat', 'populate', 'property_from_schema', 'props_from_db', 'props_to_db', 'query', 'registry', 'save_element', 'scripts', 'server_version', 'strict', 'toposort_classes', 'valid_element_base', 'vertex_from_record', 'vertexes_from_records']

If I do:

```<code>graph.delete_vertex("#21:0")
</code>```

It works good and deletes #21:0 ouser vertex row, which is part of ofriends and oworskat relationships, so also, that command deletes the relationship where that vertex is included. Obviously, I don't want to delete the entire vertex, just only the specific edge (not the class, just the relationship row).

I was wondering if exists some command like delete_edge(), but dir(graph) don't tell me nothing related.

settings.py

```<code>from pyorient.ogm import Graph, Config
from pyorient.serializations import OrientSerialization
from pyorient.ogm import declarative

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

config = RawConfigParser()
config.read(BASE_DIR + '/settings.ini')

ORIENTDB = {
    'NAME': config.get('orientdbConf', 'DB_NAME'),
    'USER': config.get('orientdbConf', 'DB_USER'),
    'PASSWORD': config.get('orientdbConf', 'DB_PASS'),
    'HOST': config.get('orientdbConf', 'DB_HOST'),
    'PORT': config.get('orientdbConf', 'DB_PORT'),
}

Config.from_url('plocal://'+ORIENTDB['HOST']+':'+str(ORIENTDB['PORT'])+'/'+ORIENTDB['NAME']+'',''+ORIENTDB['USER']+'', ''+ORIENTDB['PASSWORD']+'',initial_drop=False,serialization_type=OrientSerialization.Binary)
graph = Graph(Config.from_url(''+ORIENTDB['HOST']+'/'+ORIENTDB['NAME']+'',''+ORIENTDB['USER']+'', ''+ORIENTDB['PASSWORD']+'',initial_drop=False))
Node = declarative.declarative_node()
Relationship = declarative.declarative_relationship()
</code>```

models.py

```<code>from core.settings import Node,Relationship,graph
from pyorient.ogm.property import (String, Date, DateTime, Decimal, Double,
    Integer, Boolean, EmbeddedMap, EmbeddedSet,Link, UUID)

class OUsers(Node):
    element_plural = 'ousers'
    postgresql_id=Integer(nullable=False,unique=True)

class OCompany(Node):
    element_plural = 'ocompany'
    postgresql_id=Integer(nullable=False,unique=True)

class OFriends(Relationship):
    label = 'ofriends'
    from_postgresql_ouser_id=Integer(nullable=False,unique=True)
    to_postgresql_ouser_id=Integer(nullable=False,unique=True)

class OWorksAt(Relationship):
    label = 'oworksat'
    from_postgresql_ouser_id=Integer(nullable=False,unique=True)
    to_postgresql_ocompany_id=Integer(nullable=False,unique=True)

graph.create_all(Node.registry)
graph.create_all(Relationship.registry)
</code>```

serializers.py

```<code>from .models import (OUsers,OCompany,OFriends,OWorksAt)
from rest_framework import serializers
from django.contrib.auth import get_user_model
User = get_user_model()

class OFriendsSerializer(serializers.Serializer):
    from_postgresql_ouser_id = serializers.IntegerField()
    to_postgresql_ouser_id = serializers.IntegerField()

    def create(self, data):
        return OFriends.objects.create(**data)

    def update(self, instance, data):
        instance.from_postgresql_ouser_id = data.get("from_postgresql_ouser_id")
        instance.to_postgresql_ouser_id = data.get("to_postgresql_ouser_id")
        instance.save()
        return instance

class OFriendsSerializer(serializers.Serializer):
    from_postgresql_ouser_id = serializers.IntegerField()
    to_postgresql_ouser_id = serializers.IntegerField()

    def create(self, data):
        return OFriends.objects.create(**data)

    def update(self, instance, data):
        instance.from_postgresql_ouser_id = data.get("from_postgresql_ouser_id")
        instance.to_postgresql_ouser_id = data.get("to_postgresql_ouser_id")
        instance.save()
        return instance

</code>```

api.py

```<code>class OFriendsViewSet(viewsets.ModelViewSet):

    def destroy(self, request, *args, **kwargs):
        queryset = graph.ofriends.query()
        import pdb;pdb.set_trace()
        # HERE should be the command

</code>```

答:
An alternative to constructing the command yourself is to use Graph.record_delete() and passing it the record ID of the edge to delete.

The code snippet below assume that db is an instance of OrientDB and rid holds the record ID of the link to delete:

```<code>cluster = rid[1:].split(':')[0]
record = rid[1:].split(':')[1]
db.record_delete(cluster, record)
</code>```

As a sidebar, the more I work with OrientDB, the more I regret my choice of database given the lack of support for the Python driver which is functionally incomplete and now also very out of date.

Body:
I don't know how to create a method to delete edges in django rest framework, using orientdb OGM.

I'm using pyorient==1.5.5 and OrientDB 3.0.18 version.

I have two vertex Classes: ousers, ocompany. Also I have two relationships (edges) Classes: ofriends, oworksat. So for example:

To make a ofriends relationship, I need two ousers.
And to make a oworksat relationship, I need one ouser and one ocompany.
Every relationship has it own cluster id.

I know that I can access to these functions:

(Pdb) dir(graph)

['PROPERTY_TYPES', '_GROOVY_GET_DB', '_GROOVY_NULL_LISTENER', '_GROOVY_TRY', 'class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref', '_last_cred', '_last_db', '_last_user', 'batch', 'both', 'bothE', 'build_mapping', 'clear_registry', 'client', 'coerce_class_names', 'coerce_class_names_to_quoted', 'compute_all_properties', 'config', 'create_all', 'create_class', 'create_edge', 'create_edge_command', 'create_function', 'create_props_mapping', 'create_vertex', 'create_vertex_command', 'delete_vertex', 'delete_vertex_command', 'drop', 'drop_all', 'drop_class', 'edge_from_record', 'edges_from_records', 'element_from_link', 'element_from_record', 'elements_from_links', 'elements_from_records', 'export', 'get_edge', 'get_element', 'get_vertex', 'gremlin', 'guard_reserved_words', 'inE', 'in_', 'include', 'init_broker_for_class', 'list_superclasses', 'ocompany', 'ofriends', 'open', 'ousers', 'out', 'outE', 'oworksat', 'populate', 'property_from_schema', 'props_from_db', 'props_to_db', 'query', 'registry', 'save_element', 'scripts', 'server_version', 'strict', 'toposort_classes', 'valid_element_base', 'vertex_from_record', 'vertexes_from_records']

If I do:

graph.delete_vertex("#21:0")

It works good and deletes #21:0 ouser vertex row, which is part of ofriends and oworskat relationships, so also, that command deletes the relationship where that vertex is included. Obviously, I don't want to delete the entire vertex, just only the specific edge (not the class, just the relationship row).

I was wondering if exists some command like delete_edge(), but dir(graph) don't tell me nothing related.

settings.py

from pyorient.ogm import Graph, Config
from pyorient.serializations import OrientSerialization
from pyorient.ogm import declarative

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

config = RawConfigParser()
config.read(BASE_DIR + '/settings.ini')

ORIENTDB = {
    'NAME': config.get('orientdbConf', 'DB_NAME'),
    'USER': config.get('orientdbConf', 'DB_USER'),
    'PASSWORD': config.get('orientdbConf', 'DB_PASS'),
    'HOST': config.get('orientdbConf', 'DB_HOST'),
    'PORT': config.get('orientdbConf', 'DB_PORT'),
}

Config.from_url('plocal://'+ORIENTDB['HOST']+':'+str(ORIENTDB['PORT'])+'/'+ORIENTDB['NAME']+'',''+ORIENTDB['USER']+'', ''+ORIENTDB['PASSWORD']+'',initial_drop=False,serialization_type=OrientSerialization.Binary)
graph = Graph(Config.from_url(''+ORIENTDB['HOST']+'/'+ORIENTDB['NAME']+'',''+ORIENTDB['USER']+'', ''+ORIENTDB['PASSWORD']+'',initial_drop=False))
Node = declarative.declarative_node()
Relationship = declarative.declarative_relationship()

models.py

from core.settings import Node,Relationship,graph
from pyorient.ogm.property import (String, Date, DateTime, Decimal, Double,
    Integer, Boolean, EmbeddedMap, EmbeddedSet,Link, UUID)

class OUsers(Node):
    element_plural = 'ousers'
    postgresql_id=Integer(nullable=False,unique=True)

class OCompany(Node):
    element_plural = 'ocompany'
    postgresql_id=Integer(nullable=False,unique=True)

class OFriends(Relationship):
    label = 'ofriends'
    from_postgresql_ouser_id=Integer(nullable=False,unique=True)
    to_postgresql_ouser_id=Integer(nullable=False,unique=True)

class OWorksAt(Relationship):
    label = 'oworksat'
    from_postgresql_ouser_id=Integer(nullable=False,unique=True)
    to_postgresql_ocompany_id=Integer(nullable=False,unique=True)

graph.create_all(Node.registry)
graph.create_all(Relationship.registry)

serializers.py

from .models import (OUsers,OCompany,OFriends,OWorksAt)
from rest_framework import serializers
from django.contrib.auth import get_user_model
User = get_user_model()

class OFriendsSerializer(serializers.Serializer):
    from_postgresql_ouser_id = serializers.IntegerField()
    to_postgresql_ouser_id = serializers.IntegerField()

    def create(self, data):
        return OFriends.objects.create(**data)

    def update(self, instance, data):
        instance.from_postgresql_ouser_id = data.get("from_postgresql_ouser_id")
        instance.to_postgresql_ouser_id = data.get("to_postgresql_ouser_id")
        instance.save()
        return instance

class OFriendsSerializer(serializers.Serializer):
    from_postgresql_ouser_id = serializers.IntegerField()
    to_postgresql_ouser_id = serializers.IntegerField()

    def create(self, data):
        return OFriends.objects.create(**data)

    def update(self, instance, data):
        instance.from_postgresql_ouser_id = data.get("from_postgresql_ouser_id")
        instance.to_postgresql_ouser_id = data.get("to_postgresql_ouser_id")
        instance.save()
        return instance

api.py

class OFriendsViewSet(viewsets.ModelViewSet):

    def destroy(self, request, *args, **kwargs):
        queryset = graph.ofriends.query()
        import pdb;pdb.set_trace()
        # HERE should be the command

Body:
An alternative to constructing the command yourself is to use Graph.record_delete() and passing it the record ID of the edge to delete.

The code snippet below assume that db is an instance of OrientDB and rid holds the record ID of the link to delete:

cluster = rid[1:].split(':')[0]
record = rid[1:].split(':')[1]
db.record_delete(cluster, record)

As a sidebar, the more I work with OrientDB, the more I regret my choice of database given the lack of support for the Python driver which is functionally incomplete and now also very out of date.


问:
Flutter change Drawer UserAccountsDrawerHeader layout
I am building my first flutter application, so my question is:
Can you change the layout of the profile pic of the UserAccountsDrawerHeader, for example below image I want to put the image on the left side of the username

Here is my code

```<code>class SideMenu extends StatefulWidget {
  SideMenu({Key key}) : super(key: key);

  @override
  _SideMenuState createState() => _SideMenuState();
}

class _SideMenuState extends State<SideMenu> {
  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: Column(
        children: <Widget>[

          UserAccountsDrawerHeader(
            accountEmail: Text('@User'),
            accountName: Text('user'),
            currentAccountPicture: CircleAvatar(
              backgroundImage: AssetImage("assets/Images/profilePic.jpg"),

            ),
          ),

          ListTile(
            title: Text('hey'),
          )
        ],
       )
    );
  }
}
</code>```

答:
You can achieve it by providing Row Widget to accountName property as below code.</p>

```<code>UserAccountsDrawerHeader(
          accountEmail: Text(''), // keep blank text because email is required
          accountName: Row(
            children: <Widget>[
              Container(
                width: 50,
                height: 50,
                decoration: BoxDecoration(shape: BoxShape.circle),
                child: CircleAvatar(
                  backgroundColor: Colors.redAccent,
                  child: Icon(
                    Icons.check,
                  ),
                ),
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text('user'),
                  Text('@User'),
                ],
              ),
            ],
          ),
        ),
</code>```

Body:
I am building my first flutter application, so my question is:
Can you change the layout of the profile pic of the UserAccountsDrawerHeader, for example below image I want to put the image on the left side of the username

Here is my code

class SideMenu extends StatefulWidget {
  SideMenu({Key key}) : super(key: key);

  @override
  _SideMenuState createState() => _SideMenuState();
}

class _SideMenuState extends State<SideMenu> {
  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: Column(
        children: <Widget>[

          UserAccountsDrawerHeader(
            accountEmail: Text('@User'),
            accountName: Text('user'),
            currentAccountPicture: CircleAvatar(
              backgroundImage: AssetImage("assets/Images/profilePic.jpg"),

            ),
          ),

          ListTile(
            title: Text('hey'),
          )
        ],
       )
    );
  }
}

Body:
You can achieve it by providing Row Widget to accountName property as below code.

UserAccountsDrawerHeader(
          accountEmail: Text(''), // keep blank text because email is required
          accountName: Row(
            children: <Widget>[
              Container(
                width: 50,
                height: 50,
                decoration: BoxDecoration(shape: BoxShape.circle),
                child: CircleAvatar(
                  backgroundColor: Colors.redAccent,
                  child: Icon(
                    Icons.check,
                  ),
                ),
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text('user'),
                  Text('@User'),
                ],
              ),
            ],
          ),
        ),


问:
How can i center a Audio Player?
how can i center the audio player?

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        #playlist{
            list-style: none;
        }
        #playlist li a{
            color:white;
            text-decoration: none;
        }
        #playlist .current-song a{
            color:blue;
        }
        body {background-color: black;}
        h1 {color: white;}
        p {color: white;}
    </style>
    <link rel="shortcut icon" type="image/ico" href="/img/favicon.ico">
</head>
<body>
    <audio src="" controls autoplay id="audioPlayer">
        Sorry, your Browser doesn't Support HTML5!
    </audio>
    <ul id="playlist">
        <li class="current-song"><a href="/music/song1.mp3"></a></li>
        <li><a href="/music/song2.mp3"></a></li>
    </ul>
    <!-- <p>Back to <a href="https://URL/">URL</a></p> -->
    <script src="https://code.jquery.com/tt.js"></script>
    <script src="audioPlayer.js"></script>
    <script>
        audioPlayer();
    </script>
</body>
</html>
</code>```

This is what i have so far: https://prnt.sc/r4o3nh
And this is what i want: https://prnt.sc/r4o3en

What i tried:
style="display: block; margin: 0 auto;
style="position:absolute;top:0;left:0;width:100%;height:100%;" width="1400" height="900"

答:
Try this:</p>

```<code>audio#audioPlayer {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}
</code>```

Title: How can i center a Audio Player?

Body:
how can i center the audio player?

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

    <link rel="shortcut icon" type="image/ico" href="/img/favicon.ico">

    <audio src="" controls autoplay id="audioPlayer">
        Sorry, your Browser doesn't Support HTML5!
    </audio>

This is what i have so far: https://prnt.sc/r4o3nh
And this is what i want: https://prnt.sc/r4o3en

What i tried:
style="display: block; margin: 0 auto;
style="position:absolute;top:0;left:0;width:100%;height:100%;" width="1400" height="900"

Body:
Try this:

audio#audioPlayer {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}


问:
@RequestParam with any value
I have the following metod in my @Restcontroller:

```<code>@GetMapping
public List<User> getByParameterOrAll(
        @RequestParam(value = "email", required = false) String email,
        @RequestParam(value = "phone", required = false) String phone) {

    List<User> userList;
    if ((email != null && !email.isEmpty()) && (phone == null || phone.isEmpty())) {
        userList = super.getByEmail(email);
    } else if ((email == null || email.isEmpty()) && (phone != null)) {
        userList = super.getByPhone(phone);
    } else {
        userList = super.getAll();
    }
    return userList;
}
</code>```

This method allows to handle following GET-requests:

```<code>GET:   /customers/
GET:   /customers?email=emai@email.com
GET:   /customers?phone=8-812-872-23-34
</code>```

But if necessary to add some more parameters for request. If it will be 10 or... 20 params,body of above method arrise outrageously!
If there any way to pass value of @RequestParam to the method-body, I could realize, for example:

```<code>@GetMapping
public List<User> getByParameterOrAll(
        @RequestParam(value = "any", required = false) String any) {

    if (value=="email") {
        userList = super.getByEmail(email);
    } else if (value=="email") {
        userList = super.getByPhone(email);
    } else if .....
}
</code>```

Is there any way to use @RequestParam-value in method-body?

答:
You can just add HttpServletRequest as a method parameter and Spring will give it to you:

```<code>@GetMapping
public List<User> getByParameterOrAll(@RequestParam(value = "email", required = false)
String email,
                                      @RequestParam(value = "phone", required = false)
String phone, HttpServletRequest request)
</code>```

Then, you can use the HttpServletRequest API to get the list of parameters passed:

request.getParameterNames() or request.getParameterMap()

See the docs here:

https://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameterMap()

Title: @RequestParam with any value

Body:
I have the following metod in my @Restcontroller:

@GetMapping
public List<User> getByParameterOrAll(
        @RequestParam(value = "email", required = false) String email,
        @RequestParam(value = "phone", required = false) String phone) {

    List<User> userList;
    if ((email != null && !email.isEmpty()) && (phone == null || phone.isEmpty())) {
        userList = super.getByEmail(email);
    } else if ((email == null || email.isEmpty()) && (phone != null)) {
        userList = super.getByPhone(phone);
    } else {
        userList = super.getAll();
    }
    return userList;
}

This method allows to handle following GET-requests:

GET:   /customers/
GET:   /customers?email=emai@email.com
GET:   /customers?phone=8-812-872-23-34

But if necessary to add some more parameters for request. If it will be 10 or... 20 params,body of above method arrise outrageously!
If there any way to pass value of @RequestParam to the method-body, I could realize, for example:

@GetMapping
public List<User> getByParameterOrAll(
        @RequestParam(value = "any", required = false) String any) {

    if (value=="email") {
        userList = super.getByEmail(email);
    } else if (value=="email") {
        userList = super.getByPhone(email);
    } else if .....
}

Is there any way to use @RequestParam-value in method-body?

Body:
You can just add HttpServletRequest as a method parameter and Spring will give it to you:

@GetMapping
public List<User> getByParameterOrAll(@RequestParam(value = "email", required = false)
String email,
                                      @RequestParam(value = "phone", required = false)
String phone, HttpServletRequest request)

Then, you can use the HttpServletRequest API to get the list of parameters passed:

request.getParameterNames() or request.getParameterMap()

See the docs here:

https://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameterMap()


问:
HTML to JSON with Formatting Python
I've seen several examples of this online on how to convert HTML content to JSON, but I'm unable to get to an actual result.

Suppose I have the following html_content:

```<code><html>
    <body>
        <h1>My Heading</h1>
        <p>Hello world</p>
        <table>
            <tr>
                <th>Name</th>
                <th>Age</th>
                <th>License</th>
                <th>Amount</th>
            </tr>
            <tr>
                <td>John</td>
                <td>28</td>
                <td>Y</td>
                <td>12.30</td>
            </tr>
            <tr>
                <td>Kevin</td>
                <td>25</td>
                <td>Y</td>
                <td>22.30</td>
            </tr>
            <tr>
                <td>Smith</td>
                <td>38</td>
                <td>Y</td>
                <td>52.20</td>
            </tr>
            <tr>
                <td>Stewart</td>
                <td>21</td>
                <td>N</td>
                <td>3.80</td>
            </tr>
        </table>
    </body>
</html>
</code>```

As you can see, this contains a heading, paragraph and table elements.
I am trying to convert the above to JSON and output the result to a separate file, with correct formatting. This is my code:

```<code>import sys
import json
jsonD = json.dumps(html_content, sort_keys=True, indent=4)

sys.stdout=open("output.json","w")
print (jsonD)
sys.stdout.close()
</code>```

The result is:

```<code>"\n<html>\n\t<body>\n\t\t<h1>My Heading</h1>\n\t\t<p>Hello world</p>\n\t\t<table>\n\t\t\t<tr>\n\t\t\t\t<th>Name</th>\n\t\t\t\t<th>Age</th>\n\t\t\t\t<th>License</th>\n\t\t\t\t<th>Amount</th>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>John</td>\n\t\t\t\t<td>28</td>\n\t\t\t\t<td>Y</td>\n\t\t\t\t<td>12.30</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>Kevin</td>\n\t\t\t\t<td>25</td>\n\t\t\t\t<td>Y</td>\n\t\t\t\t<td>22.30</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>Smith</td>\n\t\t\t\t<td>38</td>\n\t\t\t\t<td>Y</td>\n\t\t\t\t<td>52.20</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td>Stewart</td>\n\t\t\t\t<td>21</td>\n\t\t\t\t<td>N</td>\n\t\t\t\t<td>3.80</td>\n\t\t\t</tr>\n\t\t</table>\n\t</body>\n</html>\n"
</code>```

As you can see, the result is not escaping any of the return or tab characters and is making the output seem like one long string. How can I rectify this so that the output is correctly formatting from a JSON perspective?

答:
You need to know how you want your json output to look like. If you want the names to be the keys, and the values be the list of everything else, I would do something like:

```<code>from bs4 import BeautifulSoup
import json

html_content = """
<table>
    <tr>
        <td>John</td>
        <td>28</td>
        <td>Y</td>
        <td>12.30</td>
    </tr>
    <tr>
        <td>Kevin</td>
        <td>25</td>
        <td>Y</td>
        <td>22.30</td>
    </tr>
    <tr>
        <td>Smith</td>
        <td>38</td>
        <td>Y</td>
        <td>52.20</td>
    </tr>
    <tr>
        <td>Stewart</td>
        <td>21</td>
        <td>N</td>
        <td>3.80</td>
    </tr>
</table>
<h1> hello world <h1>
<table>
    <tr>
        <td>Jack</td>
        <td>1</td>
    </tr>
    <tr>
        <td>Joe</td>
        <td>2</td>
    </tr>
    <tr>
        <td>Bill</td>
        <td>3</td>
    </tr>
    <tr>
        <td>Sam</td>
        <td>4</td>
    </tr>
</table>
"""

html_content_parsed = [[cell.text for cell in row("td")]
                         for row in BeautifulSoup(html_content,features="html.parser")("tr")]

html_content_dictionary = {element[0]:element[1:] for element in html_content_parsed}

print(json.dumps(html_content_dictionary, indent=4))
</code>```

As you can see, this will ignore other non-table elements and puts all the tables into json.

You can try out the program here:
https://repl.it/@Mandawi/htmltojson

Title: HTML to JSON with Formatting Python

Body:
I've seen several examples of this online on how to convert HTML content to JSON, but I'm unable to get to an actual result.

Suppose I have the following html_content:

My Heading

Hello world

                Name
                Age
                License
                Amount

                John
                28
                Y
                12.30

                Kevin
                25
                Y
                22.30

                Smith
                38
                Y
                52.20

                Stewart
                21
                N
                3.80

As you can see, this contains a heading, paragraph and table elements.
I am trying to convert the above to JSON and output the result to a separate file, with correct formatting. This is my code:

import sys
import json
jsonD = json.dumps(html_content, sort_keys=True, indent=4)

sys.stdout=open("output.json","w")
print (jsonD)
sys.stdout.close()

The result is:

"\n\n\t\n\t\t
My Heading
\n\t\t
Hello world
\n\t\t
\n\t\t\t
\n\t\t\t\tName	\n\t\t\t\tAge	\n\t\t\t\tLicense	\n\t\t\t\tAmount	\n\t\t\t
\n\t\t\t
\n\t\t\t\tJohn	\n\t\t\t\t28	\n\t\t\t\tY	\n\t\t\t\t12.30	\n\t\t\t
\n\t\t\t
\n\t\t\t\tKevin	\n\t\t\t\t25	\n\t\t\t\tY	\n\t\t\t\t22.30	\n\t\t\t
\n\t\t\t
\n\t\t\t\tSmith	\n\t\t\t\t38	\n\t\t\t\tY	\n\t\t\t\t52.20	\n\t\t\t
\n\t\t\t
\n\t\t\t\tStewart	\n\t\t\t\t21	\n\t\t\t\tN	\n\t\t\t\t3.80	\n\t\t\t
\n\t\t
\n\t\n\n"

As you can see, the result is not escaping any of the return or tab characters and is making the output seem like one long string. How can I rectify this so that the output is correctly formatting from a JSON perspective?

Body:
You need to know how you want your json output to look like. If you want the names to be the keys, and the values be the list of everything else, I would do something like:

from bs4 import BeautifulSoup
import json

html_content = """
<table>
    <tr>
        <td>John</td>
        <td>28</td>
        <td>Y</td>
        <td>12.30</td>
    </tr>
    <tr>
        <td>Kevin</td>
        <td>25</td>
        <td>Y</td>
        <td>22.30</td>
    </tr>
    <tr>
        <td>Smith</td>
        <td>38</td>
        <td>Y</td>
        <td>52.20</td>
    </tr>
    <tr>
        <td>Stewart</td>
        <td>21</td>
        <td>N</td>
        <td>3.80</td>
    </tr>
</table>
<h1> hello world <h1>
<table>
    <tr>
        <td>Jack</td>
        <td>1</td>
    </tr>
    <tr>
        <td>Joe</td>
        <td>2</td>
    </tr>
    <tr>
        <td>Bill</td>
        <td>3</td>
    </tr>
    <tr>
        <td>Sam</td>
        <td>4</td>
    </tr>
</table>
"""

html_content_parsed = [[cell.text for cell in row("td")]
                         for row in BeautifulSoup(html_content,features="html.parser")("tr")]

html_content_dictionary = {element[0]:element[1:] for element in html_content_parsed}

print(json.dumps(html_content_dictionary, indent=4))

As you can see, this will ignore other non-table elements and puts all the tables into json.

You can try out the program here:
https://repl.it/@Mandawi/htmltojson


问:
Is there a developer edition of WebSphere MQ for free download?
WebSphere Application Server 8.0 is available in a free developer edition, is there also one available for WebSphere MQ?</p>

答:
I know it is an older question, but here are my two cents:

A docker image for IBM MQ can be downloaded from hub.docker.com
This image is free to be used with development.