问:
How to prevent or remove or replace NA values in glm output statistics?
I've made up an example to illustrate my problem. Imagine I have a dataset, and I train a generalized linear model with gamma-distributed residuals.

```<code>library(MASS)

df <- read.csv('test.csv')

model <- glm(formula = y ~ method * site + year + 0,
             family=Gamma(link = "log"), data = df)
</code>```

And I get something that looks like this:

```<code>> summary(model)

Coefficients:
                  Estimate Std. Error t value Pr(>|t|)
methodM0          3.89533    0.13670  28.496  < 2e-16 ***
methodM1          5.63965    0.20940  26.933  < 2e-16 ***
methodM2        -55.854107  73.982453  -0.755    0.450
methodM3        -55.731730  73.986509  -0.753    0.451
siteS1           -0.002872   0.098226  -0.029    0.977
siteS2            0.060892   0.107795   0.565    0.572
siteS3           -0.016239   0.102258  -0.159    0.874
year              0.030813   0.036743   0.839    0.402
methodM1:siteS1  -0.030616   0.144592  -0.212    0.832
methodM2:siteS1  -0.030632   0.144663  -0.212    0.832
methodM3:siteS1   0.064179   0.145593   0.441    0.659
methodM1:siteS2  -0.146505   0.152012  -0.964    0.335
methodM2:siteS2  -0.039610   0.148024  -0.268    0.789
methodM3:siteS2  -0.202881   0.150406  -1.349    0.178
methodM1:siteS3   NA         NA         NA       NA
methodM2:siteS3   0.081617   0.144040   0.567    0.571
methodM3:siteS3  -0.064155   0.147771  -0.434    0.664

</code>```

The table is the result of made-up numbers, but the point is that I have an interaction between method M1 and site S3 that give NA. How can I setup the GLM to not calculate that particular interaction, remove that interaction after training, or set those NA values in the model to 0?

Update

@jared_mamrot gave an answer that pointed to this related question which is very similar:

```<code>s <- source("http://pastebin.com/raw.php?i=EcMEVqUC")$value

lm(income ~ age + cit * prof, data=s)
</code>```

Here lm rather than glm is followed, but I found that update didn't even seem to fix this example when I ran the accepted answer to the related problem.

```<code>model1 <- lm(income ~ age + cit * prof, data=s)
model2 <- update(model1, . ~ . - citforeign:profofficial)
</code>```

Looking at model1, we have

```<code>> model1

Call:
lm(formula = income ~ age + cit * prof, data = s)

Coefficients:
               (Intercept)                         age                     citwest                  citforeign
                  2205.231                      -3.825                      74.871                      30.066
           profblue-collar                profofficial     citwest:profblue-collar  citforeign:profblue-collar
                  -189.146                    -147.332                      27.792                     -60.223
      citwest:profofficial     citforeign:profofficial
                  -122.220                          NA
</code>```

And looking at model2 we have the same

```<code>> model1

Call:
lm(formula = income ~ age + cit * prof, data = s)

Coefficients:
               (Intercept)                         age                     citwest                  citforeign
                  2205.231                      -3.825                      74.871                      30.066
           profblue-collar                profofficial     citwest:profblue-collar  citforeign:profblue-collar
                  -189.146                    -147.332                      27.792                     -60.223
      citwest:profofficial     citforeign:profofficial
                  -122.220                          NA
</code>```

As you can see, update doesn't seem to remove the NA.

答:
Can you use update? E.g.

```<code>model1 <- glm(formula = y ~ method * site + year + 0,
             family=Gamma(link = "log"), data = df)
model2 <- update(model1, . ~ . - methodM1:siteS3)
</code>```

(per Remove some factor-interaction terms from estimation / https://www.r-bloggers.com/using-the-update-function-during-variable-selection/)

Edit

Here is a way to use the update method on the example data posted at Remove some factor-interaction terms from estimation

```<code>s <- source("http://pastebin.com/raw.php?i=EcMEVqUC")$value
model1 <- glm(income ~ age + cit * prof, data=s)
model2 <- update(model1, . ~ . - cit:prof)
summary_glm(model1)
summary_glm(model2)
</code>```

Edit 2

If you don't want to use update you could try dropping the interaction (see below) but I don't know how this will affect the validity of the model or whether it is advisable.

```<code>s <- source("http://pastebin.com/raw.php?i=EcMEVqUC")$value
model1 <- glm(income ~ age + cit * prof, data=s)
model2 <- glm(income ~ model.matrix(model1)[,1:9], data=s)
summary_glm(model1)
summary_glm(model2)
</code>```

Body:
I've made up an example to illustrate my problem. Imagine I have a dataset, and I train a generalized linear model with gamma-distributed residuals.

library(MASS)

df <- read.csv('test.csv')

model <- glm(formula = y ~ method * site + year + 0,
             family=Gamma(link = "log"), data = df)

And I get something that looks like this:

> summary(model)

Coefficients:
                  Estimate Std. Error t value Pr(>|t|)
methodM0          3.89533    0.13670  28.496  < 2e-16 ***
methodM1          5.63965    0.20940  26.933  < 2e-16 ***
methodM2        -55.854107  73.982453  -0.755    0.450
methodM3        -55.731730  73.986509  -0.753    0.451
siteS1           -0.002872   0.098226  -0.029    0.977
siteS2            0.060892   0.107795   0.565    0.572
siteS3           -0.016239   0.102258  -0.159    0.874
year              0.030813   0.036743   0.839    0.402
methodM1:siteS1  -0.030616   0.144592  -0.212    0.832
methodM2:siteS1  -0.030632   0.144663  -0.212    0.832
methodM3:siteS1   0.064179   0.145593   0.441    0.659
methodM1:siteS2  -0.146505   0.152012  -0.964    0.335
methodM2:siteS2  -0.039610   0.148024  -0.268    0.789
methodM3:siteS2  -0.202881   0.150406  -1.349    0.178
methodM1:siteS3   NA         NA         NA       NA
methodM2:siteS3   0.081617   0.144040   0.567    0.571
methodM3:siteS3  -0.064155   0.147771  -0.434    0.664

The table is the result of made-up numbers, but the point is that I have an interaction between method M1 and site S3 that give NA. How can I setup the GLM to not calculate that particular interaction, remove that interaction after training, or set those NA values in the model to 0?

Update

@jared_mamrot gave an answer that pointed to this related question which is very similar:

s <- source("http://pastebin.com/raw.php?i=EcMEVqUC")$value

lm(income ~ age + cit * prof, data=s)

Here lm rather than glm is followed, but I found that update didn't even seem to fix this example when I ran the accepted answer to the related problem.

model1 <- lm(income ~ age + cit * prof, data=s)
model2 <- update(model1, . ~ . - citforeign:profofficial)

Looking at model1, we have

> model1

Call:
lm(formula = income ~ age + cit * prof, data = s)

Coefficients:
               (Intercept)                         age                     citwest                  citforeign
                  2205.231                      -3.825                      74.871                      30.066
           profblue-collar                profofficial     citwest:profblue-collar  citforeign:profblue-collar
                  -189.146                    -147.332                      27.792                     -60.223
      citwest:profofficial     citforeign:profofficial
                  -122.220                          NA

And looking at model2 we have the same

> model1

Call:
lm(formula = income ~ age + cit * prof, data = s)

Coefficients:
               (Intercept)                         age                     citwest                  citforeign
                  2205.231                      -3.825                      74.871                      30.066
           profblue-collar                profofficial     citwest:profblue-collar  citforeign:profblue-collar
                  -189.146                    -147.332                      27.792                     -60.223
      citwest:profofficial     citforeign:profofficial
                  -122.220                          NA

As you can see, update doesn't seem to remove the NA.

Body:
Can you use update? E.g.

model1 <- glm(formula = y ~ method * site + year + 0,
             family=Gamma(link = "log"), data = df)
model2 <- update(model1, . ~ . - methodM1:siteS3)

(per Remove some factor-interaction terms from estimation / https://www.r-bloggers.com/using-the-update-function-during-variable-selection/)

Edit

Here is a way to use the update method on the example data posted at Remove some factor-interaction terms from estimation

s <- source("http://pastebin.com/raw.php?i=EcMEVqUC")$value
model1 <- glm(income ~ age + cit * prof, data=s)
model2 <- update(model1, . ~ . - cit:prof)
summary_glm(model1)
summary_glm(model2)

Edit 2

If you don't want to use update you could try dropping the interaction (see below) but I don't know how this will affect the validity of the model or whether it is advisable.

s <- source("http://pastebin.com/raw.php?i=EcMEVqUC")$value
model1 <- glm(income ~ age + cit * prof, data=s)
model2 <- glm(income ~ model.matrix(model1)[,1:9], data=s)
summary_glm(model1)
summary_glm(model2)


来源: stackexchange

问:
DataGridView DataSource Set Columns
I have the following class:

```<code>Imports Cognex.InSight
Imports Newtonsoft.Json

Public Class VariableViewModel

    Public Enum VariableTypes
        EditRegion
        Enumerated
        Input
        Momentary
        Toggle
    End Enum

    Public Property CellLocation As CvsCellLocation

    Public Property Name As String

    Public Property Values As Dictionary(Of String, String)

    Public Property VariableType As VariableTypes

    Public Function ToJson() As String
        Return JsonConvert.SerializeObject(New With {Key Name, CellLocation, Values, VariableType})
    End Function

End Class
</code>```

This class is being serialized and then eventually deserialized back and stored into a List. This list is ultimately bound to a DataGridView using a BindingSource as such:

```<code>' Private ReadOnly _variables As List(Of VariableViewModel)
Dim source As BindingSource = New BindingSource() With {
    .DataSource = _variables
}
DataGridViewVariables.DataSource = source
</code>```

The issue that I'm running into is that the Column names in the DataGridView are not a one-to-one match to the properties on the class. Plus I wanted to add two button columns at the end of the DataGridView.

Without clearing the Columns, then binding the DataGridView, and then manually setting up the Button columns, is there a way to match the column names to the class property names?

答: The DataPropertyName property of a DataGridViewColumn determines what column/property of the data source it binds to. You can add columns to the grid yourself, either in the designer or in code, and set that property for each column. Before you set the DataSource, you set AutoGenerateColumns to False and then only the existing columns will be bound as specified and no new columns will be created.

ContentLicense: CC BY-SA 4.0

Title: DataGridView DataSource Set Columns

Body:
I have the following class:

Imports Cognex.InSight
Imports Newtonsoft.Json

Public Class VariableViewModel

    Public Enum VariableTypes
        EditRegion
        Enumerated
        Input
        Momentary
        Toggle
    End Enum

    Public Property CellLocation As CvsCellLocation

    Public Property Name As String

    Public Property Values As Dictionary(Of String, String)

    Public Property VariableType As VariableTypes

    Public Function ToJson() As String
        Return JsonConvert.SerializeObject(New With {Key Name, CellLocation, Values, VariableType})
    End Function

End Class

This class is being serialized and then eventually deserialized back and stored into a List. This list is ultimately bound to a DataGridView using a BindingSource as such:

' Private ReadOnly _variables As List(Of VariableViewModel)
Dim source As BindingSource = New BindingSource() With {
    .DataSource = _variables
}
DataGridViewVariables.DataSource = source

The issue that I'm running into is that the Column names in the DataGridView are not a one-to-one match to the properties on the class. Plus I wanted to add two button columns at the end of the DataGridView.

Without clearing the Columns, then binding the DataGridView, and then manually setting up the Button columns, is there a way to match the column names to the class property names?


问:
Get enum options in laravels eloquent
In my migration file, I gave my table pages a enum field with 2 possible values (as seen below). My question is, if it's possible to select these values with Laravels Eloquent?

```<code>$table->enum('status', array('draft','published'));
</code>```

There are several Workarounds that I found, but there must be some "eloquent-native" way to handle this. My expected output would be this (that would be perfect!):

```<code>array('draft','published')
</code>```

Thank you in advance!

答:
This throws an error if the column does not exist. So I added a small check in the code</p>

```<code>public static function getPossibleEnumValues ($column) {
// Create an instance of the model to be able to get the table name
    $instance = new static;

    $arr = DB::select(DB::raw('SHOW COLUMNS FROM '.$instance->getTable().' WHERE Field = "'.$column.'"'));
    if (count($arr) == 0){
        return array();
    }
    // Pulls column string from DB
    $enumStr = $arr[0]->Type;

    // Parse string
    preg_match_all("/'([^']+)'/", $enumStr, $matches);

    // Return matches
    return isset($matches[1]) ? $matches[1] : [];
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Get enum options in laravels eloquent

Body:
In my migration file, I gave my table pages a enum field with 2 possible values (as seen below). My question is, if it's possible to select these values with Laravels Eloquent?

$table->enum('status', array('draft','published'));

There are several Workarounds that I found, but there must be some "eloquent-native" way to handle this. My expected output would be this (that would be perfect!):

array('draft','published')

Thank you in advance!

Body:
This throws an error if the column does not exist. So I added a small check in the code

public static function getPossibleEnumValues ($column) {
// Create an instance of the model to be able to get the table name
    $instance = new static;

    $arr = DB::select(DB::raw('SHOW COLUMNS FROM '.$instance->getTable().' WHERE Field = "'.$column.'"'));
    if (count($arr) == 0){
        return array();
    }
    // Pulls column string from DB
    $enumStr = $arr[0]->Type;

    // Parse string
    preg_match_all("/'([^']+)'/", $enumStr, $matches);

    // Return matches
    return isset($matches[1]) ? $matches[1] : [];
}


问:
PyCharm - Unable to save settings - Failed to save settings. Please restart PyCharm Community Edition
PyCharm is trowing this exception when I save.

```<code>WARN - mponents.impl.stores.StoreUtil - Save settings failed
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    at java.lang.String.charAt(String.java:658)
    at com.intellij.configurationStore.ApplicationStorageManager.expandMacros(ApplicationStoreImpl.kt:108)
    at com.intellij.configurationStore.StateStorageManagerImpl.createStateStorage(StateStorageManagerImpl.kt:194)
    at com.intellij.configurationStore.StateStorageManagerImpl.getOrCreateStorage(StateStorageManagerImpl.kt:150)
    at com.intellij.configurationStore.StateStorageManagerImpl.getStateStorage(StateStorageManagerImpl.kt:133)
    at com.intellij.configurationStore.StateStorageManagerImpl$startExternalization$1.setState(StateStorageManagerImpl.kt:342)
    at com.intellij.configurationStore.ComponentStoreImpl.commitComponent(ComponentStoreImpl.kt:199)
    at com.intellij.configurationStore.ComponentStoreImpl.save(ComponentStoreImpl.kt:124)
    at com.intellij.openapi.components.impl.stores.StoreUtil.save(StoreUtil.java:49)
    at com.intellij.openapi.application.impl.ApplicationImpl.saveSettings(ApplicationImpl.java:1433)
    at com.intellij.ide.SaveAndSyncHandlerImpl.doSaveDocumentsAndProjectsAndApp(SaveAndSyncHandlerImpl.java:150)
    at com.intellij.ide.SaveAndSyncHandlerImpl.saveProjectsAndDocuments(SaveAndSyncHandlerImpl.java:134)
    at com.intellij.ide.SaveAndSyncHandlerImpl$4.onFrameDeactivated(SaveAndSyncHandlerImpl.java:104)
    at com.intellij.ide.FrameStateManagerImpl.fireDeactivationEvent(FrameStateManagerImpl.java:87)
    at com.intellij.ide.FrameStateManagerImpl.access$500(FrameStateManagerImpl.java:32)
    at com.intellij.ide.FrameStateManagerImpl$2$1.run(FrameStateManagerImpl.java:72)
    at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238)
    at com.intellij.util.Alarm$Request$1.run(Alarm.java:352)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.runNextEvent(LaterInvocator.java:337)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.run(LaterInvocator.java:321)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:866)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:654)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:381)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
</code>```

And giving me this error message.

I don't think it's a problem of permissions on the .idea file or anything like that, but I'm really not sure.

I get some other errors and warnings in the stack trace, but this is the one that recurs when I try to save projects.

This problem persists when I run PyCharm CE with sudo like this
sudo -u [username] /Applications/PyCharm\ CE.app/Contents/MacOS/pycharm

Anyone got any ideas?

OS: MacOS El Capitan
Pycharm: PyCharm Community Edition 5.0.5
JRE: 1.8.0_76-release-b162 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o.

答:
I had the same problem but I solved it by running it as a super user,
ex. In Kali Linux I tried

sudo i

then I enter the pass and then I run it like this

```<code>/Documents/pycharm-2020.1.1/bin#
./pycharm.sh`
</code>```

I think pycharm need super user

Body:
PyCharm is trowing this exception when I save.

WARN - mponents.impl.stores.StoreUtil - Save settings failed
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    at java.lang.String.charAt(String.java:658)
    at com.intellij.configurationStore.ApplicationStorageManager.expandMacros(ApplicationStoreImpl.kt:108)
    at com.intellij.configurationStore.StateStorageManagerImpl.createStateStorage(StateStorageManagerImpl.kt:194)
    at com.intellij.configurationStore.StateStorageManagerImpl.getOrCreateStorage(StateStorageManagerImpl.kt:150)
    at com.intellij.configurationStore.StateStorageManagerImpl.getStateStorage(StateStorageManagerImpl.kt:133)
    at com.intellij.configurationStore.StateStorageManagerImpl$startExternalization$1.setState(StateStorageManagerImpl.kt:342)
    at com.intellij.configurationStore.ComponentStoreImpl.commitComponent(ComponentStoreImpl.kt:199)
    at com.intellij.configurationStore.ComponentStoreImpl.save(ComponentStoreImpl.kt:124)
    at com.intellij.openapi.components.impl.stores.StoreUtil.save(StoreUtil.java:49)
    at com.intellij.openapi.application.impl.ApplicationImpl.saveSettings(ApplicationImpl.java:1433)
    at com.intellij.ide.SaveAndSyncHandlerImpl.doSaveDocumentsAndProjectsAndApp(SaveAndSyncHandlerImpl.java:150)
    at com.intellij.ide.SaveAndSyncHandlerImpl.saveProjectsAndDocuments(SaveAndSyncHandlerImpl.java:134)
    at com.intellij.ide.SaveAndSyncHandlerImpl$4.onFrameDeactivated(SaveAndSyncHandlerImpl.java:104)
    at com.intellij.ide.FrameStateManagerImpl.fireDeactivationEvent(FrameStateManagerImpl.java:87)
    at com.intellij.ide.FrameStateManagerImpl.access$500(FrameStateManagerImpl.java:32)
    at com.intellij.ide.FrameStateManagerImpl$2$1.run(FrameStateManagerImpl.java:72)
    at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238)
    at com.intellij.util.Alarm$Request$1.run(Alarm.java:352)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.runNextEvent(LaterInvocator.java:337)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.run(LaterInvocator.java:321)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:866)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:654)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:381)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

And giving me this error message.

I don't think it's a problem of permissions on the .idea file or anything like that, but I'm really not sure.

I get some other errors and warnings in the stack trace, but this is the one that recurs when I try to save projects.

This problem persists when I run PyCharm CE with sudo like this
sudo -u [username] /Applications/PyCharm\ CE.app/Contents/MacOS/pycharm

Anyone got any ideas?

OS: MacOS El Capitan
Pycharm: PyCharm Community Edition 5.0.5
JRE: 1.8.0_76-release-b162 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o.

Body:
I had the same problem but I solved it by running it as a super user,
ex. In Kali Linux I tried

sudo i

then I enter the pass and then I run it like this

/Documents/pycharm-2020.1.1/bin#
./pycharm.sh`

I think pycharm need super user


问:
Function in VBA for multiple filter
Can someone help me write VBA function to get data from another worksheet using multiple filter?
Data looks something like this.

I want to write a function that extract the A1 or A2 or A3 value based on the dropdown I select. If I select A3 it should pick data from A3 column. My Filter criteria on other columns are Item, id and location. Column for Item, id and location are static. While column for A1, A2, A3 are dynamic. I want to put criteria on Ite, id and location. These are the three criteria and result should be from the fourth column. i.e. either A1 or A2 or A3 based on what I select.

I tried but couldn't figure out. Can someone help me on this, please?

答:
You don't need VBA for this but you do need to make a few preparations. I will show here what I did. There are other ways and you can choose the way you prefer.

I created a table exactly as you posted. Instead of a table you can just create a named range or you can replace the names of either in the formulas with the range's coordinates. I didn't name the table but recommend that you do if you use a table. In my example the table's name is Table1.

Within the table I created a named range comprising the cells D1:F1. I called this range "Data" but any other name will do as well. You may also move the named range entirely elsewhere if you want different captions for the columns for one reason or another. As you will see, the names are insignificant they are used to create the numbers 1, 2 and 3 from the location where they are within the named range Data.

Now I created a validation drop-down referring to a List of =Data. The effect is that I have a drop-down with A1, A2 and A3 in it. I created this drop-down in A10 of a different sheet from the one on which I have Table1.

Now I used the following formulas to extract data from row 2 of the table.

```<code>=INDEX(Table1[Item],2)
=INDEX(Table1[Location],2) or =INDEX(Table1,2,3) and
=INDEX(Table1,2,3+MATCH(A10,Data,0))
</code>```

Observe that every "2" in the above formulas refers to the 2nd row in the named range Table1. I didn't set up a range of that name but that is something Excel threw in when I created the table. However, you would like to pull data from other rows as well.

For that purpose you can use the ROW() function. This function returns the number of the row in which it resides. If it's in row 10 it will return 10, in row 11 it returns 11 etc. It's a counter. Therefore, if you entered my formulas in row 10 you can replace all the "2"s with Row()-8 and as you copy up or down you will get data from different rows, same columns.

```<code>=INDEX(Table1[Item],Row()-8)
=INDEX(Table1[Location],Row()-8) or =INDEX(Table1,Row()-8,3) and
=INDEX(Table1,Row()-8,3+MATCH(A10,Data,0))
</code>```

If your first formula isn't in row 10 you must adjust the number to be deducted according to where your formula was entered.

Title: Function in VBA for multiple filter

Body:
You don't need VBA for this but you do need to make a few preparations. I will show here what I did. There are other ways and you can choose the way you prefer.

I created a table exactly as you posted. Instead of a table you can just create a named range or you can replace the names of either in the formulas with the range's coordinates. I didn't name the table but recommend that you do if you use a table. In my example the table's name is Table1.

Within the table I created a named range comprising the cells D1:F1. I called this range "Data" but any other name will do as well. You may also move the named range entirely elsewhere if you want different captions for the columns for one reason or another. As you will see, the names are insignificant they are used to create the numbers 1, 2 and 3 from the location where they are within the named range Data.

Now I created a validation drop-down referring to a List of =Data. The effect is that I have a drop-down with A1, A2 and A3 in it. I created this drop-down in A10 of a different sheet from the one on which I have Table1.

Now I used the following formulas to extract data from row 2 of the table.

=INDEX(Table1[Item],2)
=INDEX(Table1[Location],2) or =INDEX(Table1,2,3) and
=INDEX(Table1,2,3+MATCH(A10,Data,0))

Observe that every "2" in the above formulas refers to the 2nd row in the named range Table1. I didn't set up a range of that name but that is something Excel threw in when I created the table. However, you would like to pull data from other rows as well.

For that purpose you can use the ROW() function. This function returns the number of the row in which it resides. If it's in row 10 it will return 10, in row 11 it returns 11 etc. It's a counter. Therefore, if you entered my formulas in row 10 you can replace all the "2"s with Row()-8 and as you copy up or down you will get data from different rows, same columns.

=INDEX(Table1[Item],Row()-8)
=INDEX(Table1[Location],Row()-8) or =INDEX(Table1,Row()-8,3) and
=INDEX(Table1,Row()-8,3+MATCH(A10,Data,0))

If your first formula isn't in row 10 you must adjust the number to be deducted according to where your formula was entered.


问:
Drag and drop multiple files by filter into listview
I'm currently have this code to store data to listview
I have to store first the info to textbox lines and then store them to listview.

Is there easy way without storing first textbox and directly put the files into listview?
What I want is to drag and drop or browse the multiple video ts file in the first column and then the srt in the sub column.
hope that you know what I mean. I'm rally new in listview

```<code>Sub AddToListView()
    LV.Items.Clear()
    Dim vn = vName.Lines
    Dim sn = sName.Lines
    Dim vp = vPath.Lines
    Dim sp = sPath.Lines

    Dim items As New List(Of ListViewItem)

    Dim upper = {vn.GetUpperBound(0), sn.GetUpperBound(0), vp.GetUpperBound(0), sp.GetUpperBound(0)}
    For I = 0 To upper.Min
        items.Add(New ListViewItem({vn(I), sn(I), vp(I), sp(I)}))
    Next
    LV.BeginUpdate()
    LV.Items.AddRange(items.ToArray())
    SortItems()
    LV.EndUpdate()
    AddToParam()
End Sub

Sub readFiles()
    Dim folder As String = txtinputFolder.Text
    Dim sb1 As New StringBuilder
    Dim sb2 As New StringBuilder
    Dim sb3 As New StringBuilder
    Dim sb4 As New StringBuilder

    For Each item In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
        sb1.Append(item & vbNewLine)
    Next
    vPath.Text = ""
    vPath.Text = sb1.ToString.Trim

    For Each file As String In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
        sb2.Append(Path.GetFileName(file) & vbNewLine)
    Next
    vName.Text = ""
    vName.Text = sb2.ToString.Trim

    For Each file As String In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.srt")
        sb3.Append(Path.GetFileName(file) & vbNewLine)
    Next
    sName.Text = ""
    sName.Text = sb3.ToString.Trim

    For Each item3 In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.srt")
        sb4.Append(item3 & vbNewLine)
    Next
    sPath.Text = ""
    sPath.Text = sb4.ToString.Trim
End Sub
</code>```

答:
Thank you here's my updated code:
since I want to show first the filename I tried to re-edit the code.</p>

```<code>Sub readFiles(ByVal searchdirectory As String)
        For Each FullPath In My.Computer.FileSystem.GetFiles(searchdirectory, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
            Dim parentPath As String = Path.GetDirectoryName(FullPath)
            Dim movieName As String = Path.GetFileNameWithoutExtension(FullPath)
            Dim srtPath As String = parentPath & "\" & movieName & ".srt"
            Dim allPath As String = parentPath & "\" & movieName

            If File.Exists(srtPath) Then
                LV.BeginUpdate()
                Dim lvi As New ListViewItem
                With lvi
                    .Text = movieName & ".ts" 'video filename
                    .SubItems.Add(movieName & ".srt") 'subtitle filename
                    .SubItems.Add(movieName & ".mkv") 'output filename
                    .SubItems.Add(allPath & ".ts") 'video path
                    .SubItems.Add(allPath & ".srt") 'subtitle path
                End With
                LV.Items.Add(lvi)
                LV.EndUpdate()
            Else
                MsgBox("srt file not found in the folder", vbInformation, "")
            End If
        Next
        LV.Sorting = SortOrder.Ascending
        LV.Sort()
    End Sub
</code>```

Body:
I'm currently have this code to store data to listview
I have to store first the info to textbox lines and then store them to listview.

Is there easy way without storing first textbox and directly put the files into listview?
What I want is to drag and drop or browse the multiple video ts file in the first column and then the srt in the sub column.
hope that you know what I mean. I'm rally new in listview

Sub AddToListView()
    LV.Items.Clear()
    Dim vn = vName.Lines
    Dim sn = sName.Lines
    Dim vp = vPath.Lines
    Dim sp = sPath.Lines

    Dim items As New List(Of ListViewItem)

    Dim upper = {vn.GetUpperBound(0), sn.GetUpperBound(0), vp.GetUpperBound(0), sp.GetUpperBound(0)}
    For I = 0 To upper.Min
        items.Add(New ListViewItem({vn(I), sn(I), vp(I), sp(I)}))
    Next
    LV.BeginUpdate()
    LV.Items.AddRange(items.ToArray())
    SortItems()
    LV.EndUpdate()
    AddToParam()
End Sub

Sub readFiles()
    Dim folder As String = txtinputFolder.Text
    Dim sb1 As New StringBuilder
    Dim sb2 As New StringBuilder
    Dim sb3 As New StringBuilder
    Dim sb4 As New StringBuilder

    For Each item In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
        sb1.Append(item & vbNewLine)
    Next
    vPath.Text = ""
    vPath.Text = sb1.ToString.Trim

    For Each file As String In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
        sb2.Append(Path.GetFileName(file) & vbNewLine)
    Next
    vName.Text = ""
    vName.Text = sb2.ToString.Trim

    For Each file As String In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.srt")
        sb3.Append(Path.GetFileName(file) & vbNewLine)
    Next
    sName.Text = ""
    sName.Text = sb3.ToString.Trim

    For Each item3 In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.srt")
        sb4.Append(item3 & vbNewLine)
    Next
    sPath.Text = ""
    sPath.Text = sb4.ToString.Trim
End Sub

Body:
Thank you here's my updated code:
since I want to show first the filename I tried to re-edit the code.

Sub readFiles(ByVal searchdirectory As String)
        For Each FullPath In My.Computer.FileSystem.GetFiles(searchdirectory, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
            Dim parentPath As String = Path.GetDirectoryName(FullPath)
            Dim movieName As String = Path.GetFileNameWithoutExtension(FullPath)
            Dim srtPath As String = parentPath & "\" & movieName & ".srt"
            Dim allPath As String = parentPath & "\" & movieName

            If File.Exists(srtPath) Then
                LV.BeginUpdate()
                Dim lvi As New ListViewItem
                With lvi
                    .Text = movieName & ".ts" 'video filename
                    .SubItems.Add(movieName & ".srt") 'subtitle filename
                    .SubItems.Add(movieName & ".mkv") 'output filename
                    .SubItems.Add(allPath & ".ts") 'video path
                    .SubItems.Add(allPath & ".srt") 'subtitle path
                End With
                LV.Items.Add(lvi)
                LV.EndUpdate()
            Else
                MsgBox("srt file not found in the folder", vbInformation, "")
            End If
        Next
        LV.Sorting = SortOrder.Ascending
        LV.Sort()
    End Sub


问:
What is the Context for a listener to get Info From a DialogFragment to the Parent Fragment
I've been trying to search for an answer on my own but no one seems to be talking about my exact issue. It's usually a question about the RecyclerView Adapter Listener, and I've used that and it works every time.

When I run my code, I get this error,
 java.lang.ClassCastException: com.wereworkingonit.communitystore.SettingsActivity@d180f18must implement ExampleDialogListener

which, without the try, catch block gives me
java.lang.ClassCastException: com.wereworkingonit.communitystore.SettingsActivity cannot be cast to com.wereworkingonit.communitystore.JoinStoreDialog$EngagedDialogListener, which doesn't make sense because I followed a tutorial and just translated it to Kotlin. I assume I am missing something about the difference in how Java and Kotlin.

My question is, what do I put in the listener = line in the OnAttach function?

This is where the issue comes from.

```<code>override fun onAttach(context: Context) {
        super.onAttach(context)
        try {
            listener = context as EngagedDialogListener
        } catch (e: ClassCastException) {
            throw ClassCastException(
                context.toString() +
                        "must implement ExampleDialogListener"
            )
        }
    }
</code>```

This is the Parent Activity for the Dialog

```<code>package com.wereworkingonit.communitystore

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreferenceCompat
import com.wereworkingonit.communitystore.participant.ParticipantLandingPage
import com.wereworkingonit.communitystore.user.UserLandingPage
import com.wereworkingonit.communitystore.util.FirestoreUtil

private const val TAG = "SettingsActivity"

class SettingsActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.settings_activity)
        supportFragmentManager
            .beginTransaction()
            .replace(R.id.settings, SettingsFragment())
            .commit()
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    }

    class SettingsFragment : PreferenceFragmentCompat(),
        SharedPreferences.OnSharedPreferenceChangeListener, JoinStoreDialog.EngagedDialogListener {
        private lateinit var contextForPreferences: Context
        private var engagedPreference: Boolean = false
        private lateinit var sharedPref: SharedPreferences
        private var switchPreference: SwitchPreferenceCompat? = null

        override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey)

            switchPreference = findPreference("engage")

            androidx.preference.PreferenceManager.setDefaultValues(
                contextForPreferences,
                R.xml.root_preferences,
                false
            )
            sharedPref =
                androidx.preference.PreferenceManager.getDefaultSharedPreferences(
                    contextForPreferences
                )
            engagedPreference = sharedPref.getBoolean(AppConstants.ENGAGEMENT, false)
            Log.d(TAG, "onCreate: $engagedPreference")
            FirestoreUtil.getCurrentUser {
                switchPreference!!.isChecked = it.engagement
            }
        }

        override fun onAttach(context: Context) {
            super.onAttach(context)
            contextForPreferences = context
        }

        override fun onStart() {
            super.onStart()
            androidx.preference.PreferenceManager.getDefaultSharedPreferences(contextForPreferences)
                .registerOnSharedPreferenceChangeListener(this)
        }

        override fun onStop() {
            super.onStop()
            androidx.preference.PreferenceManager.getDefaultSharedPreferences(contextForPreferences)
                .unregisterOnSharedPreferenceChangeListener(this)
        }

        override fun onPause() {
            super.onPause()
            engagedPreference = sharedPref.getBoolean(AppConstants.ENGAGEMENT, false)
            Log.d(TAG, "onPause: $engagedPreference")

            if (engagedPreference) {
                //TODO: Add welcome splash for Engagement Change
                val intent = Intent(contextForPreferences, ParticipantLandingPage::class.java)
                startActivity(intent)
            } else {
                val intent = Intent(contextForPreferences, UserLandingPage::class.java)
                startActivity(intent)
            }
        }

        override fun notThisTime(nope: Boolean) {
            FirestoreUtil.getCurrentUser {
                switchPreference!!.isChecked = nope
            }
        }

        override fun onSharedPreferenceChanged(
            sharedPreferences: SharedPreferences?,
            key: String?
        ) {
            when (key) {
                "engage" -> {
                    val joinStoreDialog = JoinStoreDialog()

                    if (switchPreference!!.isChecked) {
                        joinStoreDialog.show(childFragmentManager, "JoinStoreDialog")
                    } else {
                        FirestoreUtil.updateCurrentUser("", null, switchPreference!!.isChecked)
                    }
                    //TODO: One way trip, or what happens if the user clicks to end engagement?
                }
            }
        }
    }
}
</code>```

This is the Dialog Fragment where the listener is made

```<code>
package com.wereworkingonit.communitystore

import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import androidx.appcompat.app.AppCompatDialogFragment
import com.wereworkingonit.communitystore.participant.ParticipantLandingPage
import com.wereworkingonit.communitystore.util.FirestoreUtil
import kotlinx.android.synthetic.main.dialog_join_the_fold.view.*

class JoinStoreDialog : AppCompatDialogFragment() {
    private lateinit var sharedPreferences: SharedPreferences
    private lateinit var listener: EngagedDialogListener

    override fun onAttach(context: Context) {
        super.onAttach(context)
        try {
            listener = context as EngagedDialogListener
        } catch (e: ClassCastException) {
            throw ClassCastException(
                context.toString() +
                        "must implement ExampleDialogListener"
            )
        }
    }

    interface EngagedDialogListener {
        fun notThisTime(nope: Boolean)
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        sharedPreferences =
            androidx.preference.PreferenceManager.getDefaultSharedPreferences(
                activity
            )
        val builder = AlertDialog.Builder(activity)
        val inflater = requireActivity().layoutInflater
        val view = inflater.inflate(R.layout.dialog_join_the_fold, null)
        view.dialog_new_store_name
        view.dialog_new_store_email
        view.dialog_new_store_password

        builder.setView(view)
            .setTitle("Thank You for Joining")
            .setNegativeButton("Na, Not Now") { dialogInterface, i ->
                engagedParticipant(false)
                listener.notThisTime(false)
                dialogInterface.dismiss()
            }
            .setPositiveButton("Let's Get Started") { dialogInterface, i ->
                engagedParticipant(true)
                FirestoreUtil.updateCurrentUser("", null, true)

                val intent = Intent(activity, ParticipantLandingPage::class.java)
                startActivity(intent)
            }

        return builder.create()
    }

    private fun engagedParticipant(engagement: Boolean) {
        val editor = sharedPreferences.edit()
        editor.putBoolean(AppConstants.ENGAGEMENT, engagement)
        editor.apply()
    }

}
</code>```

答:
The Context is your Activity. If you want to reference your parent fragment, you need to use parentFragment (or, on newer versions of Fragments, use requireParentFragment() to get a non-null fragment):

```<code>override fun onAttach(context: Context) {
    super.onAttach(context)
    try {
        listener = requireParentFragment() as EngagedDialogListener
    } catch (e: ClassCastException) {
        throw ClassCastException(
            requireParentFragment().toString() +
                    "must implement ExampleDialogListener"
        )
    }
}
</code>```

Body:
I've been trying to search for an answer on my own but no one seems to be talking about my exact issue. It's usually a question about the RecyclerView Adapter Listener, and I've used that and it works every time.

When I run my code, I get this error,
 java.lang.ClassCastException: com.wereworkingonit.communitystore.SettingsActivity@d180f18must implement ExampleDialogListener

which, without the try, catch block gives me
java.lang.ClassCastException: com.wereworkingonit.communitystore.SettingsActivity cannot be cast to com.wereworkingonit.communitystore.JoinStoreDialog$EngagedDialogListener, which doesn't make sense because I followed a tutorial and just translated it to Kotlin. I assume I am missing something about the difference in how Java and Kotlin.

My question is, what do I put in the listener = line in the OnAttach function?

This is where the issue comes from.

override fun onAttach(context: Context) {
        super.onAttach(context)
        try {
            listener = context as EngagedDialogListener
        } catch (e: ClassCastException) {
            throw ClassCastException(
                context.toString() +
                        "must implement ExampleDialogListener"
            )
        }
    }

This is the Parent Activity for the Dialog

package com.wereworkingonit.communitystore

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreferenceCompat
import com.wereworkingonit.communitystore.participant.ParticipantLandingPage
import com.wereworkingonit.communitystore.user.UserLandingPage
import com.wereworkingonit.communitystore.util.FirestoreUtil

private const val TAG = "SettingsActivity"

class SettingsActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.settings_activity)
        supportFragmentManager
            .beginTransaction()
            .replace(R.id.settings, SettingsFragment())
            .commit()
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    }

    class SettingsFragment : PreferenceFragmentCompat(),
        SharedPreferences.OnSharedPreferenceChangeListener, JoinStoreDialog.EngagedDialogListener {
        private lateinit var contextForPreferences: Context
        private var engagedPreference: Boolean = false
        private lateinit var sharedPref: SharedPreferences
        private var switchPreference: SwitchPreferenceCompat? = null

        override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey)

            switchPreference = findPreference("engage")

            androidx.preference.PreferenceManager.setDefaultValues(
                contextForPreferences,
                R.xml.root_preferences,
                false
            )
            sharedPref =
                androidx.preference.PreferenceManager.getDefaultSharedPreferences(
                    contextForPreferences
                )
            engagedPreference = sharedPref.getBoolean(AppConstants.ENGAGEMENT, false)
            Log.d(TAG, "onCreate: $engagedPreference")
            FirestoreUtil.getCurrentUser {
                switchPreference!!.isChecked = it.engagement
            }
        }

        override fun onAttach(context: Context) {
            super.onAttach(context)
            contextForPreferences = context
        }

        override fun onStart() {
            super.onStart()
            androidx.preference.PreferenceManager.getDefaultSharedPreferences(contextForPreferences)
                .registerOnSharedPreferenceChangeListener(this)
        }

        override fun onStop() {
            super.onStop()
            androidx.preference.PreferenceManager.getDefaultSharedPreferences(contextForPreferences)
                .unregisterOnSharedPreferenceChangeListener(this)
        }

        override fun onPause() {
            super.onPause()
            engagedPreference = sharedPref.getBoolean(AppConstants.ENGAGEMENT, false)
            Log.d(TAG, "onPause: $engagedPreference")

            if (engagedPreference) {
                //TODO: Add welcome splash for Engagement Change
                val intent = Intent(contextForPreferences, ParticipantLandingPage::class.java)
                startActivity(intent)
            } else {
                val intent = Intent(contextForPreferences, UserLandingPage::class.java)
                startActivity(intent)
            }
        }

        override fun notThisTime(nope: Boolean) {
            FirestoreUtil.getCurrentUser {
                switchPreference!!.isChecked = nope
            }
        }

        override fun onSharedPreferenceChanged(
            sharedPreferences: SharedPreferences?,
            key: String?
        ) {
            when (key) {
                "engage" -> {
                    val joinStoreDialog = JoinStoreDialog()

                    if (switchPreference!!.isChecked) {
                        joinStoreDialog.show(childFragmentManager, "JoinStoreDialog")
                    } else {
                        FirestoreUtil.updateCurrentUser("", null, switchPreference!!.isChecked)
                    }
                    //TODO: One way trip, or what happens if the user clicks to end engagement?
                }
            }
        }
    }
}

This is the Dialog Fragment where the listener is made

package com.wereworkingonit.communitystore

import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import androidx.appcompat.app.AppCompatDialogFragment
import com.wereworkingonit.communitystore.participant.ParticipantLandingPage
import com.wereworkingonit.communitystore.util.FirestoreUtil
import kotlinx.android.synthetic.main.dialog_join_the_fold.view.*

class JoinStoreDialog : AppCompatDialogFragment() {
    private lateinit var sharedPreferences: SharedPreferences
    private lateinit var listener: EngagedDialogListener

    override fun onAttach(context: Context) {
        super.onAttach(context)
        try {
            listener = context as EngagedDialogListener
        } catch (e: ClassCastException) {
            throw ClassCastException(
                context.toString() +
                        "must implement ExampleDialogListener"
            )
        }
    }

    interface EngagedDialogListener {
        fun notThisTime(nope: Boolean)
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        sharedPreferences =
            androidx.preference.PreferenceManager.getDefaultSharedPreferences(
                activity
            )
        val builder = AlertDialog.Builder(activity)
        val inflater = requireActivity().layoutInflater
        val view = inflater.inflate(R.layout.dialog_join_the_fold, null)
        view.dialog_new_store_name
        view.dialog_new_store_email
        view.dialog_new_store_password

        builder.setView(view)
            .setTitle("Thank You for Joining")
            .setNegativeButton("Na, Not Now") { dialogInterface, i ->
                engagedParticipant(false)
                listener.notThisTime(false)
                dialogInterface.dismiss()
            }
            .setPositiveButton("Let's Get Started") { dialogInterface, i ->
                engagedParticipant(true)
                FirestoreUtil.updateCurrentUser("", null, true)

                val intent = Intent(activity, ParticipantLandingPage::class.java)
                startActivity(intent)
            }

        return builder.create()
    }

    private fun engagedParticipant(engagement: Boolean) {
        val editor = sharedPreferences.edit()
        editor.putBoolean(AppConstants.ENGAGEMENT, engagement)
        editor.apply()
    }

}

Body:
The Context is your Activity. If you want to reference your parent fragment, you need to use parentFragment (or, on newer versions of Fragments, use requireParentFragment() to get a non-null fragment):

override fun onAttach(context: Context) {
    super.onAttach(context)
    try {
        listener = requireParentFragment() as EngagedDialogListener
    } catch (e: ClassCastException) {
        throw ClassCastException(
            requireParentFragment().toString() +
                    "must implement ExampleDialogListener"
        )
    }
}


问:
Rails Advanced Constraint pass variable from Routes to Controller
Given

```<code># routes.rb
get ':friend_slug', to: 'friend#show', constraints: FriendConstraint.new

# friend_constraint.rb
def matches?(request)
  friend = Friend.find_by(slug: request.params['friend_slug'])
  friend.present?
end
</code>```

Since I already looked up and have the friend in my routing constraint, how do I save/pass my variable friend for controllers to avoid double lookup?

Currently, I'm doing the exact same line, Friend.find_by(slug: request.params['friend_slug']) in the controller.

答:
There's no clean way to carry a variable from the constraint to a controller.

The dirty way is setting an instance variable directly on the request object.

# friend_constraint.rb
def matches?(request)
  friend = Friend.find_by(slug: request.params['friend_slug'])

  return false if friend.blank?

  request.instance_variable_set('@namespace_friend', friend)
end

# friends_controller.rb
...
friend = request.instance_variable_get('@namespace_friend')
...
```

@namespace_ so you never collide with a proper request variable.

Definitely do not recommend for production, but it was an interesting exercise.

Body:
Given

# routes.rb
get ':friend_slug', to: 'friend#show', constraints: FriendConstraint.new

# friend_constraint.rb
def matches?(request)
  friend = Friend.find_by(slug: request.params['friend_slug'])
  friend.present?
end

Since I already looked up and have the friend in my routing constraint, how do I save/pass my variable friend for controllers to avoid double lookup?

Currently, I'm doing the exact same line, Friend.find_by(slug: request.params['friend_slug']) in the controller.

Body:
There's no clean way to carry a variable from the constraint to a controller.

The dirty way is setting an instance variable directly on the request object.

# friend_constraint.rb
def matches?(request)
  friend = Friend.find_by(slug: request.params['friend_slug'])

  return false if friend.blank?

  request.instance_variable_set('@namespace_friend', friend)
end

# friends_controller.rb
...
friend = request.instance_variable_get('@namespace_friend')
...

@namespace_ so you never collide with a proper request variable.

Definitely do not recommend for production, but it was an interesting exercise.


问:
In PySpark how to add a new column based upon substring of an existent column?
Want to make use of a column of "ip" in a DataFrame, containing string of IP addresses, to add a new column called "ipClass" based upon the first part of IP "aaa.bbb.ccc.ddd" :

say, if aaa < 127, then "Class A" ; if aaa == 127, then "Loopback". Omitting the rest cases for convenience.

So originally have this dataframe :

```<code>+-----+---------------+
|index|      ip       |
+-----+---------------+
|    1| 10.xx.xx.xxx  |
|    2| 127.xxx.xxx.xx|
|    3| 100.xx.xxx.xx |
|    4| 9.xx.xxx.xx   |
+-----+---------------+
</code>```

The new DataFrame I want to have is :

```<code>+-----+---------------+-----------+
|index|      ip       |   ipClass |
+-----+---------------+-----------+
|    1| 10.xx.xx.xxx  |  Class A  |
|    2| 127.xxx.xxx.xx|  Loopback |
|    3| 100.xx.xxx.xx |  Class A  |
|    4| 9.xx.xxx.xx   |  Class A  |
|    5| 129.xx.xxx.xx |  Class B  |
+-----+---------------+-----------+
</code>```

Just wondering how the below question mark part should be look like ?

```<code>    .withColumn(""ipClass", when( _?_ < 127, "Class A").when( _?_ == 127, "Loopback" )."Loopback")
</code>```

The ? part needs to take "aaa" from "aaa.bbb.ccc.ddd", and then convert to int.

Thank you in advance !

答:
There is a pyspark.sql.functions.substring(str, pos, len) function to take a substring of a string, and then cast it to int with cast:

from pyspark.sql.types import IntegerType

df.withColumn("ipClass", when(substring(col("ip"), 0, 3).cast(IntegerType()) < 127, "Class A"))

```

Body:
Want to make use of a column of "ip" in a DataFrame, containing string of IP addresses, to add a new column called "ipClass" based upon the first part of IP "aaa.bbb.ccc.ddd" :

say, if aaa < 127, then "Class A" ; if aaa == 127, then "Loopback". Omitting the rest cases for convenience.

So originally have this dataframe :

+-----+---------------+
|index|      ip       |
+-----+---------------+
|    1| 10.xx.xx.xxx  |
|    2| 127.xxx.xxx.xx|
|    3| 100.xx.xxx.xx |
|    4| 9.xx.xxx.xx   |
+-----+---------------+

The new DataFrame I want to have is :

+-----+---------------+-----------+
|index|      ip       |   ipClass |
+-----+---------------+-----------+
|    1| 10.xx.xx.xxx  |  Class A  |
|    2| 127.xxx.xxx.xx|  Loopback |
|    3| 100.xx.xxx.xx |  Class A  |
|    4| 9.xx.xxx.xx   |  Class A  |
|    5| 129.xx.xxx.xx |  Class B  |
+-----+---------------+-----------+

Just wondering how the below question mark part should be look like ?

    .withColumn(""ipClass", when( _?_ < 127, "Class A").when( _?_ == 127, "Loopback" )."Loopback")

The ? part needs to take "aaa" from "aaa.bbb.ccc.ddd", and then convert to int.

Thank you in advance !


问:
Python one liner with function
I am strengthening my understanding of one liner in Python and have some difficulties for the following one. I would like to use list comprehension to make it shorter. Any contribution would be great please.</p>

```<code>daily_prices_l = []
daily_prices_h = []
for b in bitwise_exchanges:
  try:
    high = daily_OHLCV('BTC', 'USD', exchange=b).set_index('timestamp').high
    low = daily_OHLCV('BTC', 'USD', exchange=b).set_index('timestamp').low
    daily_prices_l.append(high.rename(b))
    daily_prices_h.append(low.rename(b))
  except:
    pass
daily_prices_l = pd.concat(daily_prices_l, axis=1)
daily_prices_h = pd.concat(daily_prices_h, axis=1)
</code>```

答:
```<code>daily_prices_l = pd.concat([daily_OHLCV('BTC', 'USD', exchange=b).set_index('timestamp').low.rename(b) for b in bitwise_exchanges], axis=1)
daily_prices_h = pd.concat([daily_OHLCV('BTC', 'USD', exchange=b).set_index('timestamp').high.rename(b) for b in bitwise_exchanges], axis=1)
</code>```

Title: Python one liner with function

Body:
I am strengthening my understanding of one liner in Python and have some difficulties for the following one. I would like to use list comprehension to make it shorter. Any contribution would be great please.

daily_prices_l = []
daily_prices_h = []
for b in bitwise_exchanges:
  try:
    high = daily_OHLCV('BTC', 'USD', exchange=b).set_index('timestamp').high
    low = daily_OHLCV('BTC', 'USD', exchange=b).set_index('timestamp').low
    daily_prices_l.append(high.rename(b))
    daily_prices_h.append(low.rename(b))
  except:
    pass
daily_prices_l = pd.concat(daily_prices_l, axis=1)
daily_prices_h = pd.concat(daily_prices_h, axis=1)


问:
How can I access a return from a decorator?
I have an auth decorator, that I am using to verify tokens for logins. I would like to return the UID from the decorator but I am unsure of how to do that? Any advice? (The idea is that we can use that UID from the token to access user-specific resources on our server)

Decorator:

```<code>def check_auth(id_token):
    decoded_token = auth.verify_id_token(id_token)
    uid = decoded_token['uid']
    print(uid)
    return uid

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.headers.get("Authorization")
        if not auth or not check_auth(auth):
            message = {"error": "Authorization Required"}
            resp = message
            return resp
        return f(*args, **kwargs)

    return decorated
</code>```

答:
The return value of a decorator is what will replace the decorated function. If you return a UID from the decorator your decorated function will be replaced by the UID.

What you can do is to inject the UID into the function call:

```<code>def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.headers.get("Authorization")
        if not auth or not check_auth(auth):
            message = {"error": "Authorization Required"}
            resp = message
            return resp
        kwargs['uid'] = check_auth(auth)
        return f(*args, **kwargs)

    return decorated
</code>```

This requires all decorated functions to accept a uid argument:

```<code>@requires_auth
def decorated_function(uid):
    …
</code>```

Body:
I have an auth decorator, that I am using to verify tokens for logins. I would like to return the UID from the decorator but I am unsure of how to do that? Any advice? (The idea is that we can use that UID from the token to access user-specific resources on our server)

Decorator:

def check_auth(id_token):
    decoded_token = auth.verify_id_token(id_token)
    uid = decoded_token['uid']
    print(uid)
    return uid

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.headers.get("Authorization")
        if not auth or not check_auth(auth):
            message = {"error": "Authorization Required"}
            resp = message
            return resp
        return f(*args, **kwargs)

    return decorated

Body:
The return value of a decorator is what will replace the decorated function. If you return a UID from the decorator your decorated function will be replaced by the UID.

What you can do is to inject the UID into the function call:

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.headers.get("Authorization")
        if not auth or not check_auth(auth):
            message = {"error": "Authorization Required"}
            resp = message
            return resp
        kwargs['uid'] = check_auth(auth)
        return f(*args, **kwargs)

    return decorated

This requires all decorated functions to accept a uid argument:

@requires_auth
def decorated_function(uid):
    …


问:
Is it possible to include symbols like +,*,/ and - to encode in base64 format?
I'm using base64 encrypting of html tags due to solve a postback issue with my code. My html tag contain symbols like + , - , / or * . While decrypting the encrypted string im getting the following error :

Invalid length for a Base-64 char array.

Can anybody suggest a workaround here please?

JavaScript Calling from aspx page.

```<code> var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    function encode64(input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            }

            else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output += keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);
        }

        return output;
    }
</code>```

C# Code to decode the string @ pageload:

```<code> public string DecodeBase64String(string encodedData)
    {
        byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
        string returnValue = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);

        return returnValue;
    }
</code>```

Error can be generated by giving a simple string that contain any of the symbols i'd mentioned or even a space character.

Html String :

```<code>"<tbody id=\"selectedColumnsTbody\">\n                    <tr style=\"cursor: move;\" id=\"ExprCountryMasterID10\"><td></td><td><input id=\"chk\" checked=\"checked\" class=\"textChangeClass\" type=\"checkbox\"></td><td>CountryMaster.ID + 10</td><td><input id=\"aliastextCountryMasterID10\" class=\"aliasTextChangeClass\" value=\"\" type=\"text\"></td>><td><input id=\"hiddenIDSortCountryMasterID10\" value=\"\" type=\"hidden\"></td></tr></tbody>\n
</code>```

Calling decrypt method from cs page:

protected void Page_Load(object sender, EventArgs e)
        {

```<code>        //HtmlTextWriter htmlTable = new HtmlTextWriter();

        //htmlTable.InnerHtml = htmlContent;
        //Master.FindControl("ContentPlaceHolder1").Controls.Add(htmlTable);
        if (Session["HtmlTable"] != null)
        {

            htmlContent = Session["HtmlTable"].ToString();
            //htmlContent = htmlContent.Replace(" ", "+");
            htmlContent = DecodeBase64String(htmlContent);
            htmlTable = new HtmlGenericControl();
            ContentPlaceHolder contentPlaceHolder = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
            if (contentPlaceHolder != null)
            {
                htmlContent = "<table cellspacing=\"0\" cellpadding=\"0\" id=\"selectedColumns\" width=\"100%\">" + htmlContent + "</table>";
                htmlTable.InnerHtml = htmlContent;
                test.InnerHtml = htmlContent;
            }
        }
</code>```

}

Javascript where im calling htmlEncode
 function StoreSessionForHtml(htmlContent) {

```<code>        //            var encodedObject = htmlEncode(htmlContent);
        //            var decodedObject = htmlDecode(encodedObject);
        //htmlContent = htmlContent.replace(/ /g, "+");

        var encodedObject = encode64(htmlContent);

        var requesthtmlContentParameter = '{' +
                        'htmlContentToServer:"' + encodedObject + '"}';

        $.ajax({
            type: "POST",
            url: "Webtop.aspx/HTMLTableContent",
            data: requesthtmlContentParameter,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                //alert("Success", msg.d);
            }, //Event that'll be fired on Success
            error: function() {
               // alert("Try Again");

            } //Event that'll be fired on Error
        });
        $("#<%= HiddenHtmlContainer.ClientID %>").val(encodedObject);
    }
</code>```

答:
There shouldn't be any problems with encoding any character since you are not encoding characters, you are encoding bytes.

The error you are getting I would assume is due to the legnth of your base64 encoded string not being correct. Base 64 encoding effectively changes groups of three bytes into groups of four characters. This means that decoders will want a string to decode that is a multiple of four characters. This is achieved by using the special character "=" to pad it out. This allows the decoder to know that those bytes don't exist (as opposed to just being blank or indeed missing).

The chances are that you had a problem purely because of the number of characters in the string you were decoding.

http://base64encode.org/ may be helpful for validating the strings you are generating to check whether your problem is with the encoding or decoding.

Body:
I'm using base64 encrypting of html tags due to solve a postback issue with my code. My html tag contain symbols like + , - , / or * . While decrypting the encrypted string im getting the following error :

Invalid length for a Base-64 char array.

Can anybody suggest a workaround here please?

JavaScript Calling from aspx page.

 var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    function encode64(input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            }

            else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output += keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);
        }

        return output;
    }

C# Code to decode the string @ pageload:

 public string DecodeBase64String(string encodedData)
    {
        byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
        string returnValue = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);

        return returnValue;
    }

Error can be generated by giving a simple string that contain any of the symbols i'd mentioned or even a space character.

Html String :

"
\n
	<input id=\"chk\" checked=\"checked\" class=\"textChangeClass\" type=\"checkbox\">	CountryMaster.ID + 10	<input id=\"aliastextCountryMasterID10\" class=\"aliasTextChangeClass\" value=\"\" type=\"text\">	><input id=\"hiddenIDSortCountryMasterID10\" value=\"\" type=\"hidden\">

\n

Calling decrypt method from cs page:

protected void Page_Load(object sender, EventArgs e)
        {

        //HtmlTextWriter htmlTable = new HtmlTextWriter();

        //htmlTable.InnerHtml = htmlContent;
        //Master.FindControl("ContentPlaceHolder1").Controls.Add(htmlTable);
        if (Session["HtmlTable"] != null)
        {

            htmlContent = Session["HtmlTable"].ToString();
            //htmlContent = htmlContent.Replace(" ", "+");
            htmlContent = DecodeBase64String(htmlContent);
            htmlTable = new HtmlGenericControl();
            ContentPlaceHolder contentPlaceHolder = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
            if (contentPlaceHolder != null)
            {
                htmlContent = "
" + htmlContent + "
";
                htmlTable.InnerHtml = htmlContent;
                test.InnerHtml = htmlContent;
            }
        }

}

Javascript where im calling htmlEncode
 function StoreSessionForHtml(htmlContent) {

        //            var encodedObject = htmlEncode(htmlContent);
        //            var decodedObject = htmlDecode(encodedObject);
        //htmlContent = htmlContent.replace(/ /g, "+");

        var encodedObject = encode64(htmlContent);

        var requesthtmlContentParameter = '{' +
                        'htmlContentToServer:"' + encodedObject + '"}';

        $.ajax({
            type: "POST",
            url: "Webtop.aspx/HTMLTableContent",
            data: requesthtmlContentParameter,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                //alert("Success", msg.d);
            }, //Event that'll be fired on Success
            error: function() {
               // alert("Try Again");

            } //Event that'll be fired on Error
        });
        $("#<%= HiddenHtmlContainer.ClientID %>").val(encodedObject);
    }


问:
Updated pip successfully, but got an error message after
Recently updated pip from 20.1 to 20.1.1. It all went well except for some reason I got an error message after it. I ran pip --version to see if it was changed to 20.1.1 and it did. Should I be concerned about the error message though? I'm on Windows 10 if that makes any difference.

```<code>
C:\Users\Isabella>pip install --upgrade pip
Collecting pip
  Downloading pip-20.1.1-py2.py3-none-any.whl (1.5 MB)
     |████████████████████████████████| 1.5 MB 726 kB/s
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 20.1
    Uninstalling pip-20.1:
      Successfully uninstalled pip-20.1
ERROR: Could not install packages due to an EnvironmentError: [WinError 5] Access is denied: 'C:\\Users\\Isabella\\AppData\\Local\\Temp\\pip-uninstall-8mkzjz1n\\pip.exe'
Consider using the `--user` option or check the permissions.

C:\Users\Isabella>pip --version
pip 20.1.1 from c:\users\isabella\appdata\local\programs\python\python38\lib\site-packages\pip (python 3.8)
</code>```

EDIT: Tried doing it with --user and it said it was already up-to-date, so I guess there's nothing to worry about? Thanks for the replies.

答:
You can type the command with user permission i.e, pip install --upgrade pip --user

Or you also try by running cmd as Administrator and run pip install --upgrade pip

Hope this helps.

Body:
Recently updated pip from 20.1 to 20.1.1. It all went well except for some reason I got an error message after it. I ran pip --version to see if it was changed to 20.1.1 and it did. Should I be concerned about the error message though? I'm on Windows 10 if that makes any difference.

C:\Users\Isabella>pip install --upgrade pip
Collecting pip
  Downloading pip-20.1.1-py2.py3-none-any.whl (1.5 MB)
     |████████████████████████████████| 1.5 MB 726 kB/s
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 20.1
    Uninstalling pip-20.1:
      Successfully uninstalled pip-20.1
ERROR: Could not install packages due to an EnvironmentError: [WinError 5] Access is denied: 'C:\\Users\\Isabella\\AppData\\Local\\Temp\\pip-uninstall-8mkzjz1n\\pip.exe'
Consider using the `--user` option or check the permissions.

C:\Users\Isabella>pip --version
pip 20.1.1 from c:\users\isabella\appdata\local\programs\python\python38\lib\site-packages\pip (python 3.8)

EDIT: Tried doing it with --user and it said it was already up-to-date, so I guess there's nothing to worry about? Thanks for the replies.


问:
Error calling Flask endpoint in AWS EC2 from AWS Lambda

Summary

I have a flask server spun up with gunicorn that creates an endpoint which I want to call from an AWS lambda function. When I run a test in Lambda however, it returns

```<code>  "errorMessage": "HTTPConnectionPool(host='<ip_of_ec2>', port=8000): Max retries exceeded with url: /api/v1/my_project(Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7efec823ed60>: Failed to establish a new connection: [Errno 111] Connection refused'))",
  "errorType": "ConnectionError",
  "stackTrace": [
    "  File \"/var/lang/lib/python3.8/imp.py\", line 234, in load_module\n    return load_source(name, filename, file)\n",
...
    "  File \"/var/task/requests/adapters.py\", line 516, in send\n    raise ConnectionError(e, request=request)\n"
  ]
}
</code>```

What sort of configuration do I need to do in AWS to allow for this call or what am I missing so that the lambda function can make this connection.

What I have

It should go without saying that everything works locally (I can run curl to call the endpoint on EC2 and make a connection). Lambda and EC2 are on the same vpc and just in case the security group accepts all outbound and inbound traffic.

Lambda Function

```<code>import requests

print('Loading function')
url = 'http://<ip_of_ec2>:8000/api/v1/my_project'

def respond(err, res=None):

    return {
        'statusCode': '400' if err else res.status_code,
        'body': err.message if err else res.json(),
        'headers': {
            'Content-Type': 'application/json',
        },
    }

def call_project(claim, link):
    return requests.post(url=url, json={"claim": claim, "link": link})

def lambda_handler(event, context):

    operations = {
        'POST': lambda x: call_project(**x)
    }

    operation = event['httpMethod']
    if operation in operations:
        payload = event['queryStringParameters'] if operation == 'GET' else json.loads(event['body'])
        return respond(None, operations[operation](payload))
    else:
        return respond(ValueError('Unsupported method "{}"'.format(operation)))
</code>```

Flask Endpoint

```<code>@app.route('/api/v1/my_project', methods=['GET', 'POST'])
def my_project():
    content = request.get_json()
  ...
    return jsonify(full_pre_json)
</code>```

Gunicorn Config

```<code>bind = "0.0.0.0:8000"
workers = 1

timeout = 3 * 60  # 3 minutes
</code>```

答:
Try configuring AWS Lambda to have an execution role to interact with the aws resources in the same VPC.

Execution Role:
https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html

Tutorial:
https://docs.aws.amazon.com/lambda/latest/dg/services-rds-tutorial.html

Body:
Summary

I have a flask server spun up with gunicorn that creates an endpoint which I want to call from an AWS lambda function. When I run a test in Lambda however, it returns

  "errorMessage": "HTTPConnectionPool(host='<ip_of_ec2>', port=8000): Max retries exceeded with url: /api/v1/my_project(Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7efec823ed60>: Failed to establish a new connection: [Errno 111] Connection refused'))",
  "errorType": "ConnectionError",
  "stackTrace": [
    "  File \"/var/lang/lib/python3.8/imp.py\", line 234, in load_module\n    return load_source(name, filename, file)\n",
...
    "  File \"/var/task/requests/adapters.py\", line 516, in send\n    raise ConnectionError(e, request=request)\n"
  ]
}

What sort of configuration do I need to do in AWS to allow for this call or what am I missing so that the lambda function can make this connection.

What I have

It should go without saying that everything works locally (I can run curl to call the endpoint on EC2 and make a connection). Lambda and EC2 are on the same vpc and just in case the security group accepts all outbound and inbound traffic.

Lambda Function

import requests

print('Loading function')
url = 'http://<ip_of_ec2>:8000/api/v1/my_project'

def respond(err, res=None):

    return {
        'statusCode': '400' if err else res.status_code,
        'body': err.message if err else res.json(),
        'headers': {
            'Content-Type': 'application/json',
        },
    }

def call_project(claim, link):
    return requests.post(url=url, json={"claim": claim, "link": link})

def lambda_handler(event, context):

    operations = {
        'POST': lambda x: call_project(**x)
    }

    operation = event['httpMethod']
    if operation in operations:
        payload = event['queryStringParameters'] if operation == 'GET' else json.loads(event['body'])
        return respond(None, operations[operation](payload))
    else:
        return respond(ValueError('Unsupported method "{}"'.format(operation)))

Flask Endpoint

@app.route('/api/v1/my_project', methods=['GET', 'POST'])
def my_project():
    content = request.get_json()
  ...
    return jsonify(full_pre_json)

Gunicorn Config

bind = "0.0.0.0:8000"
workers = 1

timeout = 3 * 60  # 3 minutes


问:
How can i scrape data from a HTML table which does not have URL? href contains 'on-click' link
With pythons beautiful soup, I am trying to scrape data from the 2nd table in the following url: https://www.timeanddate.com/weather/india/bangalore/historic?month=1&year=2018

Here I want to scrape the data for the complete Jan month of 2018, The URL for the page does not change for each date. Is there a way to scrape this kind.

How do I access each table, when the 'href' does not contain the whole data even if I edit the URL.

答:
Add this piece of code in you script..

```<code>params = {
        'n': 'india/bangalore',
        'mode': 'historic',
        'hd': '20180101',
        'month': '1',
        'year': '2018',
     }
   response = requests.get('https://www.timeanddate.com/scripts/cityajax.php',
   params=params)
</code>```

It returns a html table..
Now try changing the parameters to get desired output.

For example - 1st January 2018 >> 'hd': '20180101',
              2nd January 2018 >> 'hd': '20180102' and so on..
Hope its helpfull for you!!

Body:
Add this piece of code in you script..

params = {
        'n': 'india/bangalore',
        'mode': 'historic',
        'hd': '20180101',
        'month': '1',
        'year': '2018',
     }
   response = requests.get('https://www.timeanddate.com/scripts/cityajax.php',
   params=params)

It returns a html table..
Now try changing the parameters to get desired output.

For example - 1st January 2018 >> 'hd': '20180101',
              2nd January 2018 >> 'hd': '20180102' and so on..
Hope its helpfull for you!!


问:
How to round a number up or down in Rust?
How to floor or ceil numbers?  I tried to use the round crate but either it doesn't work or I'm using it wrong.

use round::round_down;

fn main() {
  println!("{}", round_down(5.5f64, 0));
}
```

<p>This prints <code>5.5</code> but should print <code>5</code>.</p>

<p>My <code>Cargo.toml</code> file contains this:</p>

```[dependencies]
round = "0.1.0"
```

答:
As stated in the comments you can use: floor and ceil

fn main() {
    let num_32 = 3.14159_f32;

    println!("{}", num_32.floor()); // Output: 3
    println!("{}", num_32.ceil()); // Output: 4

    let num_64 = 3.14159_f64;

    println!("{}", num_64.floor()); // Output: 3
    println!("{}", num_64.ceil()); // Output: 4
}
```

Body:
How to floor or ceil numbers?  I tried to use the round crate but either it doesn't work or I'm using it wrong.

use round::round_down;

fn main() {
  println!("{}", round_down(5.5f64, 0));
}

This prints 5.5 but should print 5.

My Cargo.toml file contains this:

[dependencies]
round = "0.1.0"


问:
I am getting this kind of error whenever i running this code
My Code:-
one_hot_encoder = OneHotEncoder(categorical_features=[0])

The Error shown:
TypeError: __init__() got an unexpected keyword argument 'categorical_features'

答:
OneHotEncoder doesn't have a parameter name categorical_features.

After defining the one_hot_encoder=OneHotEncoder() object, use the fit_transform() method to encode the categorical data.

Visit this for more..


问:
How do I solve this Javascript/CSS problem?
I want the smaller div box to show up in the larger div.

However, when I drag and drop it, this is what it looks like:

Why isn't the small box's border properly showing in the larger box? I have modified the drop function so that it copies the 2nd div instead of dropping it.

```<code><html>
    <head>
        <script>
            function remove(id){
                //var el = document.getElementById("r1").outerHTML = "";
                var element = document.getElementById(id);
                element.parentNode.parentNode.removeChild(element.parentNode);
                console.log('Removed')
            }

            function allowDrop(ev) {
                ev.preventDefault();
            }

            function drag(ev) {
                ev.dataTransfer.setData("text", ev.target.id);
            }

            function drop(ev) {
                ev.preventDefault();
                var data = ev.dataTransfer.getData("text");
                var nodeCopy = document.getElementById(data).cloneNode(true);
                nodeCopy.id = 'something';
                ev.target.appendChild(nodeCopy);
            }
        </script>
    </head>
    <body>
        <p>Drag the W3Schools image into the rectangle:</p>
        <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
        <br>
        <div id = "drag1" draggable="true" ondragstart="drag(event)" height="50px" width="50px">
            <span id="yo" class="fa fa-close cross" onclick="remove(this.id);"></span>
        </div>
    </body>
</html>
</code>```

答:
Hey @Presence as I check the thing which you are saying is working with the HTML and JS which you provided which concludes that you don't have any problem in javascript. Maybe you are facing this issue because of CSS.

You can use the CSS mentioned in the answer or else you can upload your CSS in question from which we can find out which property is giving you the issue.

function remove(id) {
  //var el = document.getElementById("r1").outerHTML = "";
  var element = document.getElementById(id);
  element.parentNode.parentNode.removeChild(element.parentNode);
  console.log("Removed");
}
function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  var nodeCopy = document.getElementById(data).cloneNode(true);
  nodeCopy.id = "something";
  ev.target.appendChild(nodeCopy);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dropDiv {
   height: 15vh;
   border: 2px solid grey;
}

.dragDiv {
   height: 9vh;
   border: 2px solid grey;
   width: 53vw;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <title>Document</title>

Drag the W3Schools image into the rectangle:

```

Body:
I want the smaller div box to show up in the larger div.

However, when I drag and drop it, this is what it looks like:

Why isn't the small box's border properly showing in the larger box? I have modified the drop function so that it copies the 2nd div instead of dropping it.

Drag the W3Schools image into the rectangle:

Body:
Hey @Presence as I check the thing which you are saying is working with the HTML and JS which you provided which concludes that you don't have any problem in javascript. Maybe you are facing this issue because of CSS.

You can use the CSS mentioned in the answer or else you can upload your CSS in question from which we can find out which property is giving you the issue.

function remove(id) {
  //var el = document.getElementById("r1").outerHTML = "";
  var element = document.getElementById(id);
  element.parentNode.parentNode.removeChild(element.parentNode);
  console.log("Removed");
}
function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  var nodeCopy = document.getElementById(data).cloneNode(true);
  nodeCopy.id = "something";
  ev.target.appendChild(nodeCopy);
}

.dropDiv {
   height: 15vh;
   border: 2px solid grey;
}

.dragDiv {
   height: 9vh;
   border: 2px solid grey;
   width: 53vw;
}

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <title>Document</title>
</head>

<body>
    <p>Drag the W3Schools image into the rectangle:</p>

    <div class="dropDiv" id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
    <br>
    <div class="dragDiv" id="drag1" draggable="true" ondragstart="drag(event)" height="50px" width="50px">
        <span id="yo" class="fa fa-close cross" onclick="remove(this.id);"></span>
    </div>
    <script src="./index.js"></script>
</body>

</html>


问:
Early Stop callback in keras
How can one effectively stop the fit process of a training model via callback in keras? Thus far I have tried various approaches including the one below.

```<code>class EarlyStoppingCallback(tf.keras.callbacks.Callback):
    def __init__(self, threshold):
        super(EarlyStoppingCallback, self).__init__()
        self.threshold = threshold

    def on_epoch_end(self, epoch, logs=None):
        accuracy = logs["accuracy"]
        if accuracy >= self.threshold:
            print("Stopping early!")
            self.model.stop_training = True
</code>```

The callback is executed, however the self.model.stop_training = True does not seem to have an effect. The print succeeds, but the model continues training. Any idea how to resolve this issue?
My tensorflow version is: tensorflow==1.14.0

答:
You're probably affected by the following issue: https://github.com/tensorflow/tensorflow/issues/37587.

In short - whenever model.predict or model.evaluate are called, model.stop_training is reset to False. I was able to reproduce this behavior using your EarlyStoppingCallback followed by another callback which was calling model.predict on some fixed dataset.

The workaround is to put callbacks which are calling model.predict or model.evaluate first before any callbacks which might want to set model.stop_training to True. It also looks like the issue was fixed in TF 2.2.

Title: Early Stop callback in keras

Body:
How can one effectively stop the fit process of a training model via callback in keras? Thus far I have tried various approaches including the one below.

class EarlyStoppingCallback(tf.keras.callbacks.Callback):
    def __init__(self, threshold):
        super(EarlyStoppingCallback, self).__init__()
        self.threshold = threshold

    def on_epoch_end(self, epoch, logs=None):
        accuracy = logs["accuracy"]
        if accuracy >= self.threshold:
            print("Stopping early!")
            self.model.stop_training = True

The callback is executed, however the self.model.stop_training = True does not seem to have an effect. The print succeeds, but the model continues training. Any idea how to resolve this issue?
My tensorflow version is: tensorflow==1.14.0


问:
Displaying all elements of a vector

First for loop

```  int i;
  for (i = 0; i <= vec.size(); i++) {
    if (vec.size() == 0) {
      cout << "[] The list is Empty" << endl;
    } else {
      cout << vec[i] << " ";
    }
  }
}
```

Second for loop

```cout << "[ ";
for(auto num : vec)
  cout << num << " ";
cout << "]";
```

Why is it that when I display all the elements in a vector using the first for loop I get "0" at the end of the vector. However, when I use the range for loop, I do not get the zero.

答:
In the first loop, when i reaches vec.size(), vec[i] is out of bounds of vec, which leads to undefined behaviour (UB). You need to change the loop condition from i<=vec.size() to i<vec.size().

Also, your check for vec.size() == 0 inside of the loop will never be true. That check needs to be moved above the loop.

```<code>if (vec.size() == 0) {
    cout << "[] The list is Empty" << endl;
}
for (i=0; i<vec.size(); i++) {
    cout <<vec[i] << " ";
}
</code>```

On the other hand, ranged-based for loop iterates over all the elements exactly and keep us away from such troubles.

Title: Displaying all elements of a vector

Body:
First for loop

  int i;
  for (i = 0; i <= vec.size(); i++) {
    if (vec.size() == 0) {
      cout << "[] The list is Empty" << endl;
    } else {
      cout << vec[i] << " ";
    }
  }
}

Second for loop

cout << "[ ";
for(auto num : vec)
  cout << num << " ";
cout << "]";

Why is it that when I display all the elements in a vector using the first for loop I get "0" at the end of the vector. However, when I use the range for loop, I do not get the zero.

Body:
In the first loop, when i reaches vec.size(), vec[i] is out of bounds of vec, which leads to undefined behaviour (UB). You need to change the loop condition from i<=vec.size() to i<vec.size().

Also, your check for vec.size() == 0 inside of the loop will never be true. That check needs to be moved above the loop.

if (vec.size() == 0) {
    cout << "[] The list is Empty" << endl;
}
for (i=0; i<vec.size(); i++) {
    cout <<vec[i] << " ";
}

On the other hand, ranged-based for loop iterates over all the elements exactly and keep us away from such troubles.