问:
After Running Macro Excel will not close, sheet will not scroll, and arrow key causes selection to jump wildly
I have created a report template that allows users to select various filters and then creates specific reports based on those filters. Below is the code for the filter selection button:

```<code>Sub Filter_Select()
 rptSelect.Show
End Sub
</code>```

After this, users are presented with UserForms to select different filters. Each UserForm calls the next user form until they reach the last UserForm whose code is such:

```<code>Private Sub UserForm_Activate()
    With milSelect
        .Top = Application.Top + 250
        .Left = Application.Left + 250
    End With
End Sub
--------------------------------------------------
Private Sub UserForm_Initialize()
    milDV.RowSource = Range("Q1:Q8").Address
End Sub
--------------------------------------------------
Private Sub CancelmilSelect_Click()
    Unload Me
End Sub
--------------------------------------------------
Private Sub OKmilSelect_Click()
    Sheets("Report Selection").Unprotect
    Range("B6").ClearContents

    Range("B6") = milDV.Text

    Unload Me

    Call Create_Report
End Sub
</code>```

Once they select the final filter, the Create_Report macro is run to determine which reports to create and what formulas to use based on the filters selected. The code is as such:

```<code>Option Explicit
Sub Create_Report()
'
'   Macro to update fields in different reporting sections after user selects report type
'

'
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
'
'   Display Tabs
'
    Dim z As Integer
        For z = 2 To Worksheets.Count
            Sheets(z).Visible = xlSheetHidden
        Next z
    If Range("B1").Value = "National" And Range("B6") = "Military" Then
        Sheets("Program Summary").Visible = xlSheetVisible
    Else
        If Range("B1") = "National" Then
            Sheets("Program Summary").Visible = xlSheetVisible
            Sheets("Family & Household Demographics").Visible = xlSheetVisible
            Sheets("Registered Member Dues").Visible = xlSheetVisible
        Else
            Sheets("Program Summary").Visible = xlSheetVisible
            Sheets("Summary").Visible = xlSheetVisible
            Sheets("Financial Summary").Visible = xlSheetVisible
        End If
    End If
'
'   Financial Summary
'
    If Sheets("Financial Summary").Visible = True Then
    Sheets("Financial Summary").Select
    Sheets("Financial Summary").Unprotect
'
'       Name Ranges
'
        Dim Operating_Expenses, Income_Private1, Income_Private2, Income_Private3, Income_Gov, Income_Other1, Income_Other2 As Range
        Set Operating_Expenses = Range("C5:C7")
        Set Income_Private1 = Range("C13")
        Set Income_Private2 = Range("C14:C16")
        Set Income_Private3 = Range("C17")
        Set Income_Gov = Range("C19:C22")
        Set Income_Other1 = Range("C25:C26")
        Set Income_Other2 = Range("C27:C30")
'
'       State Non-Military Financial Summary
'
        If Worksheets("Report Selection").Range("B1").Value = "State" Then
            If Worksheets("Report Selection").Range("B6").Value = "Non-Military" Then
                Range("B1").Value = Worksheets("Report Selection").Range("B4").Value
                Range("C1").Value = "Non-Military"
                Operating_Expenses.Formula = "=SUMIFS(INDEX('Financial Data'!$BE:$BG, 0, ROW(1:1)),'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
                Income_Private1.Formula = "=SUMIFS(INDEX('Financial Data'!$AO:$AO, 0, ROW(1:1)),'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
                Income_Private2.Formula = "=SUMIFS(INDEX('Financial Data'!$AL:$AN, 0, ROW(1:1)),'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
                Income_Private3.Formula = "=SUMIFS(INDEX('Financial Data'!$AQ:$AQ, 0, ROW(1:1)),'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
                Income_Gov.Formula = "=SUMIFS(INDEX('Financial Data'!$BA:$BD, 0, ROW(1:1)),'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
                Range("C24").Formula = "=SUMIFS('Financial Data'!$AP:$AP,'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
                Income_Other1.Formula = "=SUMIFS(INDEX('Financial Data'!$AV:$AW, 0, ROW(1:1)),'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
                Income_Other2.Formula = "=SUMIFS(INDEX('Financial Data'!$AR:$AU, 0, ROW(1:1)),'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
                Range("C31").Formula = "=SUMIFS('Financial Data'!$AZ:$AZ,'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
                Range("C32").Formula = "=SUMIFS('Financial Data'!$AY:$AY,'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
                Range("C33").Formula = "=SUMIFS('Financial Data'!$AK:$AK,'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
            End If
        End If
    End If
'
'   Select First Sheet of Report
'
    Dim i As Integer
    Dim ws As Worksheet
    For i = 1 To Worksheets.Count
        If Sheets(i).Visible = True Then
            Sheets(i).Protect
        End If
    Next i
    For i = 2 To Worksheets.Count
        If Sheets(i).Visible = True Then
            Sheets(i).Select
            Exit For
        End If
    Next i
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
End Sub
</code>```

All of the code runs properly and the reports are created, but I'm having a bug where when I try to scroll on the sheet that is displayed after the code runs, the scroll bar moves but the cells seem stuck in place. If I try to select a cell and move with the arrow key, the selection jumps around. Both of these things are solved by going to another sheet and then coming back.

Additionally, after this code runs, I cannot close Excel with any method other than through Task Manager. Since none of this happens when I first open the workbook, I am left to assume that my above code is somehow causing this.

答:
Sorry it took so long to get back to this. I've been swamped the past week. Anyways, I've finally solved the problem thanks to some direction from @Comintern. Basically, I took all of the grunt work out of each of my forms and put it in the Module that the filter button calls.

Not only is this a more streamlined and efficient way to work with the code, it also provides a centralized location to assess any errors that may crop-up essentially eliminating a few possible points of failure. Below is both the code for the filter button and the code for one of the filter forms.

New form code:

```<code>Private Sub UserForm_Activate()
    With milSelect
        .Top = Application.Top + 250
        .Left = Application.Left + 250
    End With
End Sub
---------------------------------------------------
Private Sub UserForm_Initialize()
    milDV.RowSource = Range("Q1:Q8").Address
End Sub
Private Sub CancelmilSelect_Click()
Unload Me
End Sub
---------------------------------------------------
Private Sub OKmilSelect_Click()
    Sheets("Report Selection").Unprotect
    Range("B6").ClearContents

    Range("B6") = milDV.Text

    Me.Hide
End Sub
</code>```

Filter button code:

```<code>Sub Filter_Select()
    Dim ReportType As String
    Dim Region As String
    Dim ServiceUnit As String
    Dim State As String
    Dim Military As String

    With New rptSelect
        .Show vbModal
        If Not Cancel = True Then
            If Range("B1").Value = "National" Then
                With New milSelect
                    .Show vbModal
                    If Not Cancel = True Then
                        Unload rptSelect
                        Unload milSelect
                        Call Create_Report
                    End If
                End With
            Else
                If Range("B1").Value = "Service Unit" Then
                    With New SUSelect
                        .Show vbModal
                        If Not Cancel = True Then
                            With New milSelect
                                .Show vbModal
                                If Not Cancel = True Then
                                    Unload rptSelect
                                    Unload milSelect
                                    Unload SUSelect
                                    Call Create_Report
                                End If
                            End With
                        End If
                    End With
                    Else
                        If Range("B1").Value = "Regional" Then
                            With New rgnSelect
                                .Show vbModal
                                If Not Cancel = True Then
                                    With New milSelect
                                        .Show vbModal
                                        If Not Cancel = True Then
                                            Unload rptSelect
                                            Unload milSelect
                                            Unload rgnSelect
                                            Call Create_Report
                                        End If
                                    End With
                                End If
                            End With
                            Else
                                If Range("B1").Value = "State" Then
                                    With New stateSelect
                                        .Show vbModal
                                        If Not Cancel = True Then
                                            With New milSelect
                                                .Show vbModal
                                                If Not Cancel = True Then
                                                    Unload rptSelect
                                                    Unload milSelect
                                                    Unload stateSelect
                                                    Call Create_Report
                                                End If
                                            End With
                                        End If
                                    End With
                                End If
                            End If
                        End If
            End If
        End If
    End With
End Sub
</code>```

I'm sure there is probably a cleaner way to write this other than how it appears here and welcome any suggestions anyone may have for making it look better, but for now at least, it is working like a charm. Thanks for everyone's input and patience.

Body:
I have created a report template that allows users to select various filters and then creates specific reports based on those filters. Below is the code for the filter selection button:

Sub Filter_Select()
 rptSelect.Show
End Sub

After this, users are presented with UserForms to select different filters. Each UserForm calls the next user form until they reach the last UserForm whose code is such:

Private Sub UserForm_Activate()
    With milSelect
        .Top = Application.Top + 250
        .Left = Application.Left + 250
    End With
End Sub
--------------------------------------------------
Private Sub UserForm_Initialize()
    milDV.RowSource = Range("Q1:Q8").Address
End Sub
--------------------------------------------------
Private Sub CancelmilSelect_Click()
    Unload Me
End Sub
--------------------------------------------------
Private Sub OKmilSelect_Click()
    Sheets("Report Selection").Unprotect
    Range("B6").ClearContents

    Range("B6") = milDV.Text

    Unload Me

    Call Create_Report
End Sub

Once they select the final filter, the Create_Report macro is run to determine which reports to create and what formulas to use based on the filters selected. The code is as such:

Option Explicit
Sub Create_Report()
'
'   Macro to update fields in different reporting sections after user selects report type
'

'
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
'
'   Display Tabs
'
    Dim z As Integer
        For z = 2 To Worksheets.Count
            Sheets(z).Visible = xlSheetHidden
        Next z
    If Range("B1").Value = "National" And Range("B6") = "Military" Then
        Sheets("Program Summary").Visible = xlSheetVisible
    Else
        If Range("B1") = "National" Then
            Sheets("Program Summary").Visible = xlSheetVisible
            Sheets("Family & Household Demographics").Visible = xlSheetVisible
            Sheets("Registered Member Dues").Visible = xlSheetVisible
        Else
            Sheets("Program Summary").Visible = xlSheetVisible
            Sheets("Summary").Visible = xlSheetVisible
            Sheets("Financial Summary").Visible = xlSheetVisible
        End If
    End If
'
'   Financial Summary
'
    If Sheets("Financial Summary").Visible = True Then
    Sheets("Financial Summary").Select
    Sheets("Financial Summary").Unprotect
'
'       Name Ranges
'
        Dim Operating_Expenses, Income_Private1, Income_Private2, Income_Private3, Income_Gov, Income_Other1, Income_Other2 As Range
        Set Operating_Expenses = Range("C5:C7")
        Set Income_Private1 = Range("C13")
        Set Income_Private2 = Range("C14:C16")
        Set Income_Private3 = Range("C17")
        Set Income_Gov = Range("C19:C22")
        Set Income_Other1 = Range("C25:C26")
        Set Income_Other2 = Range("C27:C30")
'
'       State Non-Military Financial Summary
'
        If Worksheets("Report Selection").Range("B1").Value = "State" Then
            If Worksheets("Report Selection").Range("B6").Value = "Non-Military" Then
                Range("B1").Value = Worksheets("Report Selection").Range("B4").Value
                Range("C1").Value = "Non-Military"
                Operating_Expenses.Formula = "=SUMIFS(INDEX('Financial Data'!$BE:$BG, 0, ROW(1:1)),'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
                Income_Private1.Formula = "=SUMIFS(INDEX('Financial Data'!$AO:$AO, 0, ROW(1:1)),'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
                Income_Private2.Formula = "=SUMIFS(INDEX('Financial Data'!$AL:$AN, 0, ROW(1:1)),'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
                Income_Private3.Formula = "=SUMIFS(INDEX('Financial Data'!$AQ:$AQ, 0, ROW(1:1)),'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
                Income_Gov.Formula = "=SUMIFS(INDEX('Financial Data'!$BA:$BD, 0, ROW(1:1)),'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
                Range("C24").Formula = "=SUMIFS('Financial Data'!$AP:$AP,'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
                Income_Other1.Formula = "=SUMIFS(INDEX('Financial Data'!$AV:$AW, 0, ROW(1:1)),'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
                Income_Other2.Formula = "=SUMIFS(INDEX('Financial Data'!$AR:$AU, 0, ROW(1:1)),'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
                Range("C31").Formula = "=SUMIFS('Financial Data'!$AZ:$AZ,'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
                Range("C32").Formula = "=SUMIFS('Financial Data'!$AY:$AY,'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
                Range("C33").Formula = "=SUMIFS('Financial Data'!$AK:$AK,'Financial Data'!$E:$E,$B$1,'Financial Data'!$H:$H,""0"")"
            End If
        End If
    End If
'
'   Select First Sheet of Report
'
    Dim i As Integer
    Dim ws As Worksheet
    For i = 1 To Worksheets.Count
        If Sheets(i).Visible = True Then
            Sheets(i).Protect
        End If
    Next i
    For i = 2 To Worksheets.Count
        If Sheets(i).Visible = True Then
            Sheets(i).Select
            Exit For
        End If
    Next i
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
End Sub

All of the code runs properly and the reports are created, but I'm having a bug where when I try to scroll on the sheet that is displayed after the code runs, the scroll bar moves but the cells seem stuck in place. If I try to select a cell and move with the arrow key, the selection jumps around. Both of these things are solved by going to another sheet and then coming back.

Additionally, after this code runs, I cannot close Excel with any method other than through Task Manager. Since none of this happens when I first open the workbook, I am left to assume that my above code is somehow causing this.

Body:
Sorry it took so long to get back to this. I've been swamped the past week. Anyways, I've finally solved the problem thanks to some direction from @Comintern. Basically, I took all of the grunt work out of each of my forms and put it in the Module that the filter button calls.

Not only is this a more streamlined and efficient way to work with the code, it also provides a centralized location to assess any errors that may crop-up essentially eliminating a few possible points of failure. Below is both the code for the filter button and the code for one of the filter forms.

New form code:

Private Sub UserForm_Activate()
    With milSelect
        .Top = Application.Top + 250
        .Left = Application.Left + 250
    End With
End Sub
---------------------------------------------------
Private Sub UserForm_Initialize()
    milDV.RowSource = Range("Q1:Q8").Address
End Sub
Private Sub CancelmilSelect_Click()
Unload Me
End Sub
---------------------------------------------------
Private Sub OKmilSelect_Click()
    Sheets("Report Selection").Unprotect
    Range("B6").ClearContents

    Range("B6") = milDV.Text

    Me.Hide
End Sub

Filter button code:

Sub Filter_Select()
    Dim ReportType As String
    Dim Region As String
    Dim ServiceUnit As String
    Dim State As String
    Dim Military As String

    With New rptSelect
        .Show vbModal
        If Not Cancel = True Then
            If Range("B1").Value = "National" Then
                With New milSelect
                    .Show vbModal
                    If Not Cancel = True Then
                        Unload rptSelect
                        Unload milSelect
                        Call Create_Report
                    End If
                End With
            Else
                If Range("B1").Value = "Service Unit" Then
                    With New SUSelect
                        .Show vbModal
                        If Not Cancel = True Then
                            With New milSelect
                                .Show vbModal
                                If Not Cancel = True Then
                                    Unload rptSelect
                                    Unload milSelect
                                    Unload SUSelect
                                    Call Create_Report
                                End If
                            End With
                        End If
                    End With
                    Else
                        If Range("B1").Value = "Regional" Then
                            With New rgnSelect
                                .Show vbModal
                                If Not Cancel = True Then
                                    With New milSelect
                                        .Show vbModal
                                        If Not Cancel = True Then
                                            Unload rptSelect
                                            Unload milSelect
                                            Unload rgnSelect
                                            Call Create_Report
                                        End If
                                    End With
                                End If
                            End With
                            Else
                                If Range("B1").Value = "State" Then
                                    With New stateSelect
                                        .Show vbModal
                                        If Not Cancel = True Then
                                            With New milSelect
                                                .Show vbModal
                                                If Not Cancel = True Then
                                                    Unload rptSelect
                                                    Unload milSelect
                                                    Unload stateSelect
                                                    Call Create_Report
                                                End If
                                            End With
                                        End If
                                    End With
                                End If
                            End If
                        End If
            End If
        End If
    End With
End Sub

I'm sure there is probably a cleaner way to write this other than how it appears here and welcome any suggestions anyone may have for making it look better, but for now at least, it is working like a charm. Thanks for everyone's input and patience.


来源: stackexchange

问:
Uploading a file to Azure using UploadFromFile
I have an ASP.NET Web Forms application.

In one of my form, I am downloading a PDF from Azure and it is displayed using rasteredge (a PDF Viewer), this allow me to add and save annotation on the PDF.

The file with annotation is then saved in a folder at the root of my application (RasterEdge_Cache).
I would like to upload the PDF back into Azure, using the UploadFromFile function.

This is the function that I am using:

```<code>public static void UploadFile(DTO.BlobUpload b)
{
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["SN_ZEUXYS"]);
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = blobClient.GetContainerReference(b.Container);
    CloudBlockBlob blockBlob = container.GetBlockBlobReference(b.FileName);
    // b.FilePath = "~/RasterEdge_Cache/193304798925/output/A-0002-00008-00205Anno.pdf"
    blockBlob.UploadFromFile(b.FilePath);
}
</code>```

This is the error message that I get:

An exception of type 'System.IO.DirectoryNotFoundException' occurred
  in mscorlib.dll but was not handled in user code Additional
  information: Could not find a part of the path 'C:\Program Files
  (x86)\IIS
  Express\~\RasterEdge_Cache\193304798925\output\A-0002-00008-00205Anno.pdf'.

I assume that the file path is not correct, what path should I use, or am I using UploadFromFile correctly?

Thank you for your help.

答:
An exception of type 'Microsoft.WindowsAzure.Storage.StorageException' occurred in Microsoft.WindowsAzure.Storage.dll but was not handled in user code Additional information: The remote server returned an error: (404) Not Found. So the question is, am I using the correct function: UploadFromFile? blockBlob.UploadFromFile(b.FilePath);

According to this article, the "The remote server returned an error: (404) Not Found." occurs when a upload operation against a container fails because the container or the blob is not found.

So I suggest you could firstly check the "b.Container,b.FileName"'s value is existing or you could use CreateIfNotExists method.

More details, you could refer to below codes.Hope it gives you some tips.

```<code> protected void Button5_Click(object sender, EventArgs e)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse("connection string");
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            //check the b.Container value is right and exists
            CloudBlobContainer container = blobClient.GetContainerReference("foobar");
            CloudBlockBlob blockBlob = container.GetBlockBlobReference("TestFile.pdf");
            HttpContext httpContext = HttpContext.Current;
            HttpServerUtility server = httpContext.Server;
            string FilePath = server.MapPath("~/test/TestFile.pdf");
            //by using this code will create the container if not exists
            container.CreateIfNotExists();
            blockBlob.UploadFromFile(FilePath);
         }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an ASP.NET Web Forms application.

In one of my form, I am downloading a PDF from Azure and it is displayed using rasteredge (a PDF Viewer), this allow me to add and save annotation on the PDF.

The file with annotation is then saved in a folder at the root of my application (RasterEdge_Cache).
I would like to upload the PDF back into Azure, using the UploadFromFile function.

This is the function that I am using:

public static void UploadFile(DTO.BlobUpload b)
{
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["SN_ZEUXYS"]);
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = blobClient.GetContainerReference(b.Container);
    CloudBlockBlob blockBlob = container.GetBlockBlobReference(b.FileName);
    // b.FilePath = "~/RasterEdge_Cache/193304798925/output/A-0002-00008-00205Anno.pdf"
    blockBlob.UploadFromFile(b.FilePath);
}

This is the error message that I get:

An exception of type 'System.IO.DirectoryNotFoundException' occurred
  in mscorlib.dll but was not handled in user code Additional
  information: Could not find a part of the path 'C:\Program Files
  (x86)\IIS
  Express\~\RasterEdge_Cache\193304798925\output\A-0002-00008-00205Anno.pdf'.

I assume that the file path is not correct, what path should I use, or am I using UploadFromFile correctly?

Thank you for your help.

Body:
An exception of type 'Microsoft.WindowsAzure.Storage.StorageException' occurred in Microsoft.WindowsAzure.Storage.dll but was not handled in user code Additional information: The remote server returned an error: (404) Not Found. So the question is, am I using the correct function: UploadFromFile? blockBlob.UploadFromFile(b.FilePath);

According to this article, the "The remote server returned an error: (404) Not Found." occurs when a upload operation against a container fails because the container or the blob is not found.

So I suggest you could firstly check the "b.Container,b.FileName"'s value is existing or you could use CreateIfNotExists method.

More details, you could refer to below codes.Hope it gives you some tips.

 protected void Button5_Click(object sender, EventArgs e)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse("connection string");
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            //check the b.Container value is right and exists
            CloudBlobContainer container = blobClient.GetContainerReference("foobar");
            CloudBlockBlob blockBlob = container.GetBlockBlobReference("TestFile.pdf");
            HttpContext httpContext = HttpContext.Current;
            HttpServerUtility server = httpContext.Server;
            string FilePath = server.MapPath("~/test/TestFile.pdf");
            //by using this code will create the container if not exists
            container.CreateIfNotExists();
            blockBlob.UploadFromFile(FilePath);
         }


问:
How do I hide the next/today/previous navigation in jQuery DatePicker and turn off animations?
How do I hide the prev/today/next navigation in jQuery DatePicker?

I'm happy with just the Month and Year drop down boxes.

Also how do I disable the animations?

@tvanfosson - I already tried hideIfNoPrevNext but that only works if you don't have a date range that spans two months.

The duration option did the trick at turning off the animations though.

Cheers.

答:
I too experienced this problem with DatePicker's default functionality.
I was missing the link to jquery.ui.base.css. After including a ref to this file on my page, it worked like a charm. I did not have to tweak any css or did not have to set any property. Fyi.</p>

OwnerDisplayName: Kev

LastEditorDisplayName: Kev

ContentLicense: CC BY-SA 2.5


问:
AngularJS: How to change the path after refresh the page
What I want: if the user reloads the page with his redirect to another page.

(Only when updating the page)

Example:
I'm on main/bla and reload the page and I'm redirected to the main/

```<code>window.onbeforeunload = function(e) {
 $state.go('main');
};
</code>```

Does not work for me.

答:
There is a lot happening when you want to change states.

For one, it could trigger extra network activities such as resource download. There isn't enough time for angular to change states, change URL and go through the lifecycle of navigating routes.

some options:

Do the redirect after the refresh happens (save something in localstorage, cookies, ..)

Redirect manually, update document.location or similar

Body:
What I want: if the user reloads the page with his redirect to another page.

(Only when updating the page)

Example:
I'm on main/bla and reload the page and I'm redirected to the main/

window.onbeforeunload = function(e) {
 $state.go('main');
};

Does not work for me.


问:
"An error occured when executing the cache:clear --no-warmup" while installing symfony-cmf-standard
I was trying to install symfony-cmf-standard using:

```<code>composer.phar create-project symfony-cmf/standard-edition symfony-cmf-standard/ --stability=dev
</code>```

But I am getting the following error:

```<code>Could not open input file: app/console
Script sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache handling the post-install-cmd event terminated with an exception

[RuntimeException]
An error occured when executing the cache:clear --no-warmup
</code>```

I am running the command as an Administrator so it should not be a permission issue.

答:
On my side with php7.0 I had to install :

php7.0-mbstring

php7.0-xml

Then it worked :)

Body:
I was trying to install symfony-cmf-standard using:

composer.phar create-project symfony-cmf/standard-edition symfony-cmf-standard/ --stability=dev

But I am getting the following error:

Could not open input file: app/console
Script sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache handling the post-install-cmd event terminated with an exception

[RuntimeException]
An error occured when executing the cache:clear --no-warmup

I am running the command as an Administrator so it should not be a permission issue.


问:
JSF: How to not show the element id in validation messages?
I have a simple JSF form with some validation on the input text.  Something like:

```<code><h:inputText id="firstName" value="#{userHandler.user.firstName} required="true" />
<h:message for="firstName" />
</code>```

Works fine.  Except that the error message looks like this:

"j_id786643870_20c27c0a:firstName: Validation Error: Value is required."

How do I tell JSF not to show the element id of the element and just show the text message?

That is, I only want it to say:

"Validation Error: Value is required."

答:
I'm using PrimeFaces 6.0, and you can actually set requiredMessage, converterMessage, and validatorMessage on the components themselves, when applicable. From the documentation:

Looks like BalusC is finally out of date. :P

Body:
I have a simple JSF form with some validation on the input text.  Something like:

<h:inputText id="firstName" value="#{userHandler.user.firstName} required="true" />
<h:message for="firstName" />

Works fine.  Except that the error message looks like this:

"j_id786643870_20c27c0a:firstName: Validation Error: Value is required."

How do I tell JSF not to show the element id of the element and just show the text message?

That is, I only want it to say:

"Validation Error: Value is required."


问:
Delphi: How to get the address of a static record
```<code>    type
      TMyRecord = record
      private
        class constructor create;
      public
        class var MyField1: string;
        class var MyField2: integer;
        class var MyField3: extended;
        class function ToString: string; static;
      end;

    class constructor TMyRecord.Create;
    begin
        TMyRecord.MyField1 := 'Hello, world!';
        TMyRecord.MyField2 := 123;
        TMyRecord.MyField3 := 3.1415927;
    end;

    class function TMyRecord.ToString: string;
    var
      RecType: TRTTIType;
      RecFields: TArray<TRttiField>;
      I: integer;
    begin
      RecType := TRTTIContext.Create.GetType(TypeInfo(TMyRecord));
      Result := RecType.ToString;
      RecFields := RecType.GetFields;
      for I := 0 to High(RecFields) do
        Result := Result + Format('%s: %s = %s', [RecFields[I].Name, RecFields[I].FieldType.ToString, RecFields[I].GetValue(@TMyRecord).ToString]) + sLineBreak;
    end;
</code>```

I am trying to get TMyRecord.ToString to return:

```<code>    TMyRecord
    MyField1: string = Hello, world!
    MyField2: integer = 123;
    MyField3: extended = 3.1415927;
</code>```

However, I get a compiler error on GetValue(@TMyRecord) - E2029 '(' expected but ')' found

Normally GetValue should be called with the address of the 'instance' of the record. But in this case the record is static.
I do not want to convert this record to a normal record, create an instance etc. I'm trying to solve this for a static record.
How can I get the address that should be passed to GetValue?

答:
As said in another answer, it is not possible to get access to class var fields with RTTI.

But with a small adjustment it is still possible to get the wanted solution:

```<code>program TestClassVar;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,System.RTTI;

type
  TMyRecord = record
    type
      TIR = record
        MyField1: string;
        MyField2: integer;
        MyField3: extended;
      end;
  private
    class constructor create;
  public
    class var r: TIR;
    class function ToString: string; static;
  end;

class constructor TMyRecord.Create;
begin
  TMyRecord.r.MyField1 := 'Hello, world!';
  TMyRecord.r.MyField2 := 123;
  TMyRecord.r.MyField3 := 3.1415927;
end;

class function TMyRecord.ToString: string;
var
  RecType: TRTTIType;
  RecFields: TArray<TRttiField>;
  I: integer;
  firstFieldAdr: Pointer;
begin
  RecType := TRTTIContext.Create.GetType(TypeInfo(TMyRecord));
  Result := RecType.ToString + sLineBreak;
  RecType := TRTTIContext.Create.GetType(TypeInfo(TIR));
  RecFields := RecType.GetFields;

  firstFieldAdr := Addr(TMyRecord.r);
  for I := 0 to High(RecFields) do
    Result :=
      Result +
      Format('%s: %s = %s',
        [RecFields[I].Name,
        RecFields[I].FieldType.ToString,
        RecFields[I].GetValue(firstFieldAdr).ToString])
        +
      sLineBreak;
end;

begin
  WriteLn(TMyRecord.ToString);
  ReadLn;
end.
</code>```

The fields are put into an inner record and the address of the first field is resolved via the Addr() function.

The drawback is that the access to the fields will have an extra r. specifier.

Actual output:

```<code>TMyRecord
MyField1: string = Hello, world!
MyField2: Integer = 123
MyField3: Extended = 3.1415927
</code>```

Body:
    type
      TMyRecord = record
      private
        class constructor create;
      public
        class var MyField1: string;
        class var MyField2: integer;
        class var MyField3: extended;
        class function ToString: string; static;
      end;

    class constructor TMyRecord.Create;
    begin
        TMyRecord.MyField1 := 'Hello, world!';
        TMyRecord.MyField2 := 123;
        TMyRecord.MyField3 := 3.1415927;
    end;

    class function TMyRecord.ToString: string;
    var
      RecType: TRTTIType;
      RecFields: TArray<TRttiField>;
      I: integer;
    begin
      RecType := TRTTIContext.Create.GetType(TypeInfo(TMyRecord));
      Result := RecType.ToString;
      RecFields := RecType.GetFields;
      for I := 0 to High(RecFields) do
        Result := Result + Format('%s: %s = %s', [RecFields[I].Name, RecFields[I].FieldType.ToString, RecFields[I].GetValue(@TMyRecord).ToString]) + sLineBreak;
    end;

I am trying to get TMyRecord.ToString to return:

    TMyRecord
    MyField1: string = Hello, world!
    MyField2: integer = 123;
    MyField3: extended = 3.1415927;

However, I get a compiler error on GetValue(@TMyRecord) - E2029 '(' expected but ')' found

Normally GetValue should be called with the address of the 'instance' of the record. But in this case the record is static.
I do not want to convert this record to a normal record, create an instance etc. I'm trying to solve this for a static record.
How can I get the address that should be passed to GetValue?

Body:
As said in another answer, it is not possible to get access to class var fields with RTTI.

But with a small adjustment it is still possible to get the wanted solution:

program TestClassVar;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,System.RTTI;

type
  TMyRecord = record
    type
      TIR = record
        MyField1: string;
        MyField2: integer;
        MyField3: extended;
      end;
  private
    class constructor create;
  public
    class var r: TIR;
    class function ToString: string; static;
  end;

class constructor TMyRecord.Create;
begin
  TMyRecord.r.MyField1 := 'Hello, world!';
  TMyRecord.r.MyField2 := 123;
  TMyRecord.r.MyField3 := 3.1415927;
end;

class function TMyRecord.ToString: string;
var
  RecType: TRTTIType;
  RecFields: TArray<TRttiField>;
  I: integer;
  firstFieldAdr: Pointer;
begin
  RecType := TRTTIContext.Create.GetType(TypeInfo(TMyRecord));
  Result := RecType.ToString + sLineBreak;
  RecType := TRTTIContext.Create.GetType(TypeInfo(TIR));
  RecFields := RecType.GetFields;

  firstFieldAdr := Addr(TMyRecord.r);
  for I := 0 to High(RecFields) do
    Result :=
      Result +
      Format('%s: %s = %s',
        [RecFields[I].Name,
        RecFields[I].FieldType.ToString,
        RecFields[I].GetValue(firstFieldAdr).ToString])
        +
      sLineBreak;
end;

begin
  WriteLn(TMyRecord.ToString);
  ReadLn;
end.

The fields are put into an inner record and the address of the first field is resolved via the Addr() function.

The drawback is that the access to the fields will have an extra r. specifier.

Actual output:

TMyRecord
MyField1: string = Hello, world!
MyField2: Integer = 123
MyField3: Extended = 3.1415927


问:
Send data from more than one form with ajax to the same controller
I have a select form that will send the selected value to the controller, and a form modal that will send two values to the same controller, all of these two will be sending their data with jquery functions!
here is my code :

```<code>HTML:
<!DOCTYPE html>
    <html>
        <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
          <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
          <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
        <![endif]-->
      </head>
      <body>

    <div class="form-group">
                         <h3>Veuillez choisir un cycle :</h3><br/>

                          <label>Cycle: </label>

                          <form method="post" accept-charset="utf-8">

                         <select name="cyc" id ="Select1" class="input-small">

                            <?php foreach($cycle as $row) {?>

                                 <option value="<?php echo $row->id; ?>"><?php echo $row->libelle; ?></option>

                            <?php }?>
                        </select>

                          </form>

                          <button class="btn btn-success" onclick="display()"><i class="glyphicon glyphicon-plus"></i> display</button>
                        </div>

      <div id="x" style="display:none;" class="container">

    </center>

        <button class="btn btn-success" onclick="add_filiere()"><i class="glyphicon glyphicon-plus"></i> Ajouter une filiere</button>
        <br />
        <br />

        <table id="table_id" class="table table-striped table-bordered" cellspacing="0" width="100%">
          <thead>
            <tr>
                     <th>Identifiant</th>
              <th>Identifiant du cycle</th>
              <th>Libellé</th>

              <th>Action</th>
            </tr>
          </thead>
          <tbody>
                    <?php foreach($filiere as $row){?>
                         <tr>
                             <td><?php echo $row->id;?></td>
                      <td><?php echo $row->id_cycle;?></td>
                             <td><?php echo $row->libelle;?></td>

                                    <td>
                                        <button class="btn btn-warning" onclick="edit_filiere(<?php echo $row->id;?>)"><i class="glyphicon glyphicon-pencil"></i></button>
                                        <button class="btn btn-danger" onclick="delete_filiere(<?php echo $row->id;?>)"><i class="glyphicon glyphicon-remove"></i></button>

                                    </td>
                          </tr>
                         <?php }?>

          </tbody>

        </table>

      </div>

      <script src="<?php echo base_url('assests/datatables/js/jquery.dataTables.min.js')?>"></script>
      <script src="<?php echo base_url('assests/datatables/js/dataTables.bootstrap.js')?>"></script>

      <script type="text/javascript">
      $(document).ready( function () {
          $('#table_id').DataTable( {
            "lengthMenu": [[5,10, 25, 50, -1], [5,10, 25, 50, "All"]]
        });
      } );
        var save_method; //for save method string
        var table;

        function add_filiere()
        {
          save_method = 'add';
          $('#form')[0].reset(); // reset form on modals
          $('#modal_form').modal('show'); // show bootstrap modal
        //$('.modal-title').text('Add Person'); // Set Title to Bootstrap modal title
        }

        function display()
        {
       /*  var ic = document.getElementById('cyc').value;
         document.getElementById('x').style.display = 'block';

         $.ajax({
           url : "<?php echo site_url('index.php/filiere/test') ?>",
           type :"POST",
            data :{ic: ic},
            success: function(data)
            {

            },
            error : function(jqXHR, textStatus, errorThrown)
            {
              alert('cannot reach controller');
            }

         });*/
        }

        function edit_filiere(id)
        {
          save_method = 'update';
          $('#form')[0].reset(); // reset form on modals

          //Ajax Load data from ajax
          $.ajax({
            url : "<?php echo site_url('index.php/filiere/filiere_edit/')?>/" + id,
            type: "GET",
            dataType: "JSON",
            success: function(data)
            {

                $('[name="i"]').val(data.id);
                $('[name="l"]').val(data.libelle);

                $('#modal_form').modal('show'); // show bootstrap modal when complete loaded
                $('.modal-title').text('Modifier département'); // Set title to Bootstrap modal title

            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                alert('Error get data from ajax');
            }
        });
        }

        function save()
        {
          var url;
          if(save_method == 'add')
          {
              url = "<?php echo base_url('index.php/filiere/filiere_add')?>";
          }
          else
          {
            url = "<?php echo base_url('index.php/filiere/filiere_update')?>";
          }

           // ajax adding data to database
              $.ajax({
                url : url,
                type: "POST",
                data: $('#form').serialize(),
                dataType: "JSON",
                success: function(data)
                {
                   //if success close modal and reload ajax table
                   $('#modal_form').modal('hide');
                  location.reload();// for reload a page
                },
                error: function (jqXHR, textStatus, errorThrown)
                {
                    alert('Error adding / update data');
                }
            });
        }

        function delete_filiere(id)
        {
          if(confirm('Voulez vous supprimer ce filiere ?'))
          {
            // ajax delete data from database
              $.ajax({
                url : "<?php echo site_url('index.php/filiere/filiere_delete')?>/"+id,
                type: "POST",
                dataType: "JSON",
                success: function(data)
                {

                   location.reload();
                },
                error: function (jqXHR, textStatus, errorThrown)
                {
                    alert('Error deleting data');
                }
            });

          }
        }

      </script>

      <!-- Bootstrap modal -->
      <div class="modal fade" id="modal_form" role="dialog">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
            <h3 class="modal-title">Départements</h3>
          </div>
          <div class="modal-body form">
            <form action="#" id="form" class="form-horizontal">

              <div class="form-body">
                <div class="form-group">
                  <label class="control-label col-md-3">Identifiant</label>
                  <div class="col-md-9">
                    <input name="i" placeholder="Identifiant" class="form-control" type="text">
                  </div>
                </div>
                <div class="form-group">
                  <label class="control-label col-md-3">Libelle</label>
                  <div class="col-md-9">
                    <input name="l" placeholder="Nom" class="form-control" type="text">
                  </div>
                </div>

              </div>
            </form>
              </div>
              <div class="modal-footer">
                <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
                <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
              </div>
            </div><!-- /.modal-content -->
          </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->
      <!-- End Bootstrap modal -->

      </body>
    </html>
</code>```

My controller:

```<code><?php
            defined('BASEPATH') OR exit('No direct script access allowed');

            class Filiere extends CI_Controller {

                /**
                 * Index Page for this controller.
                 *
                 * Maps to the following URL
                 *      http://example.com/index.php/welcome
                 *  - or -
                 *      http://example.com/index.php/welcome/index
                 *  - or -
                 * Since this controller is set as the default controller in
                 * config/routes.php, it's displayed at http://example.com/
                 *
                 * So any other public methods not prefixed with an underscore will
                 * map to /index.php/welcome/<method_name>
                 * @see https://codeigniter.com/user_guide/general/urls.html
                 */

                 public function __construct()
                    {
                        parent::__construct();
                        $this->load->helper('url');
                        $this->load->model('filiere_model');
                        $this->load->model('cycle_model');

                    }

                public function index()
                {
                    $this->data["cycle"] = $this->cycle_model->get_all_cycle();
                   $id_cycle = "";
                    $this->data['filiere'] = $this->filiere_model->get_all_filiere($id_cycle);
                    $this->data["title"] = "Gérer les filieres";
                    $this->data["page"] = $this->load->view('filiere_view',$this->data,true);
                    $this->load->view("default",$this->data);
                }
            public function test()
             {
                  $id_cycle = $_POST['ic'];
                  $this->data['x']= $id_cycle;
                  $this->data["page"] = $this->load->view('test_view',$this->data,true);
                  $this->load->view("default",$this->data);
            }
                public function filiere_add()
                    {
                        $data = array(
                                'id' => $this->input->post('i'),
                                 'id_cycle' => $this->input->post('cyc'),
                                  'libelle' => $this->input->post('l'),

                            );
                        $insert = $this->filiere_model->filiere_add($data);
                        echo json_encode(array("status" => TRUE));
                    }
                    public function filiere_edit($id)
                    {
                        $data = $this->filiere_model->get_by_id($id);

                        echo json_encode($data);
                    }

                    public function filiere_update()
                {
                    $data = array(
                                'id' => $this->input->post('i'),
                                'libelle' => $this->input->post('l')

                            );
                    $this->filiere_model->filiere_update(array('id' => $this->input->post('i')), $data);
                    echo json_encode(array("status" => TRUE));
                }

                public function filiere_delete($id)
                {
                    $this->filiere_model->delete_by_id($id);
                    echo json_encode(array("status" => TRUE));
                }

            }
</code>```

Please help!

答:
Controller:

```<code> $this->input->post('name');
 $this->input->post('location');
</code>```

Ajax:

```<code>$.ajax({
  method: "POST",
  url: "your/controller",
  data: { name: "John", location: "Boston" }
})
  .done(function( msg ) {
    alert( "Data Saved: " + msg );
  });
</code>```

Body:
I have a select form that will send the selected value to the controller, and a form modal that will send two values to the same controller, all of these two will be sending their data with jquery functions!
here is my code :

HTML:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

Veuillez choisir un cycle :

                          Cycle:

                          <form method="post" accept-charset="utf-8">

                         <select name="cyc" id ="Select1" class="input-small">

                            <?php foreach($cycle as $row) {?>

                                 <option value="<?php echo $row->id; ?>"><?php echo $row->libelle; ?></option>

                            <?php }?>
                        </select>

                          </form>

                          <button class="btn btn-success" onclick="display()"> display</button>

        <button class="btn btn-success" onclick="add_filiere()"> Ajouter une filiere</button>

                     Identifiant
              Identifiant du cycle
              Libellé

              Action

                    <?php foreach($filiere as $row){?>

                             <?php echo $row->id;?>
                      <?php echo $row->id_cycle;?>
                             <?php echo $row->libelle;?>

                                        <button class="btn btn-warning" onclick="edit_filiere(<?php echo $row->id;?>)"></button>
                                        <button class="btn btn-danger" onclick="delete_filiere(<?php echo $row->id;?>)"></button>

                         <?php }?>

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Départements

            <form action="#" id="form" class="form-horizontal">

                  Identifiant

                    <input name="i" placeholder="Identifiant" class="form-control" type="text">

                  Libelle

                    <input name="l" placeholder="Nom" class="form-control" type="text">

            </form>

                <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
                <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>

My controller:

<?php
            defined('BASEPATH') OR exit('No direct script access allowed');

            class Filiere extends CI_Controller {

                /**
                 * Index Page for this controller.
                 *
                 * Maps to the following URL
                 *      http://example.com/index.php/welcome
                 *  - or -
                 *      http://example.com/index.php/welcome/index
                 *  - or -
                 * Since this controller is set as the default controller in
                 * config/routes.php, it's displayed at http://example.com/
                 *
                 * So any other public methods not prefixed with an underscore will
                 * map to /index.php/welcome/<method_name>
                 * @see https://codeigniter.com/user_guide/general/urls.html
                 */

                 public function __construct()
                    {
                        parent::__construct();
                        $this->load->helper('url');
                        $this->load->model('filiere_model');
                        $this->load->model('cycle_model');

                    }

                public function index()
                {
                    $this->data["cycle"] = $this->cycle_model->get_all_cycle();
                   $id_cycle = "";
                    $this->data['filiere'] = $this->filiere_model->get_all_filiere($id_cycle);
                    $this->data["title"] = "Gérer les filieres";
                    $this->data["page"] = $this->load->view('filiere_view',$this->data,true);
                    $this->load->view("default",$this->data);
                }
            public function test()
             {
                  $id_cycle = $_POST['ic'];
                  $this->data['x']= $id_cycle;
                  $this->data["page"] = $this->load->view('test_view',$this->data,true);
                  $this->load->view("default",$this->data);
            }
                public function filiere_add()
                    {
                        $data = array(
                                'id' => $this->input->post('i'),
                                 'id_cycle' => $this->input->post('cyc'),
                                  'libelle' => $this->input->post('l'),

                            );
                        $insert = $this->filiere_model->filiere_add($data);
                        echo json_encode(array("status" => TRUE));
                    }
                    public function filiere_edit($id)
                    {
                        $data = $this->filiere_model->get_by_id($id);

                        echo json_encode($data);
                    }

                    public function filiere_update()
                {
                    $data = array(
                                'id' => $this->input->post('i'),
                                'libelle' => $this->input->post('l')

                            );
                    $this->filiere_model->filiere_update(array('id' => $this->input->post('i')), $data);
                    echo json_encode(array("status" => TRUE));
                }

                public function filiere_delete($id)
                {
                    $this->filiere_model->delete_by_id($id);
                    echo json_encode(array("status" => TRUE));
                }

            }

Please help!

Body:
Controller:

 $this->input->post('name');
 $this->input->post('location');

Ajax:

$.ajax({
  method: "POST",
  url: "your/controller",
  data: { name: "John", location: "Boston" }
})
  .done(function( msg ) {
    alert( "Data Saved: " + msg );
  });


问:
How to end a quiz using java script timer
I am trying to design a simple quiz application using simple HTML code and a JavaScript, I want the quiz to jump to the final score when the speculated time elapse. I have been able to set up the timer but its not executing what I really want and I don't know where to go from here. I will be so glad  if anyone can find time to look in it.</p>

答:
You can use a timeout, that execute a code after a time.
https://www.w3schools.com/jsref/met_win_settimeout.asp</p>


问:
textIsSelectable not working with Edittext
I have seen many question like this here and lots of solution but nothing is working for me. below is my EditText xml

```<code>        <EditText
        android:id="@+id/summary_edittextview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="10dp"
        android:lines="15"
        android:maxLength="1000"
        android:textIsSelectable="true"
        android:textSize="16dp"
        android:backgroundTint="@color/colorPrimaryDark"/>
</code>```

I tried to do textIsSelectable=true which makes edittext disable and nothing happens, I tried using cursorVisible=true but that also does not solve my problem. Please help i want to allow user to copy text which is inside EditText

More Details:-
This EditText is under layout of fragment and I am using this style as app theme

```<code>  <style name="AppTheme.Dark" parent="Theme.AppCompat.Light.NoActionBar">
</code>```

even if i remove textIsSelectable=true it doesn't work. Please help me where i am doing mistake.

答: Your code worked for me when I removed android:textIsSelectable="true". </p>

Body:
I have seen many question like this here and lots of solution but nothing is working for me. below is my EditText xml

        <EditText
        android:id="@+id/summary_edittextview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="10dp"
        android:lines="15"
        android:maxLength="1000"
        android:textIsSelectable="true"
        android:textSize="16dp"
        android:backgroundTint="@color/colorPrimaryDark"/>

I tried to do textIsSelectable=true which makes edittext disable and nothing happens, I tried using cursorVisible=true but that also does not solve my problem. Please help i want to allow user to copy text which is inside EditText

More Details:-
This EditText is under layout of fragment and I am using this style as app theme


问:
cordova-plugin-facebook4 don't send logEvent
I'm using ionic with plugin cordova-plugin-facebook4.
When I try to use logEvent() I didn't receive any error and also didn't get the information to my Facebook analytics.

I used logEvent() in the following way:

```<code>facebookConnectPlugin.logEvent('my event name', {}, 1);
</code>```

答:
Using arbitrary Strings as Event names are allowed. For e.g.

```<code>Facebook.logEvent('InvoicePage', {}, 1).then(function (value) {console.log('fulfilled logevent'); }, function (reason) {console.log('failed logevent'); });;
</code>```

where Facebook is referred from :

```<code>import {Facebook} from "ionic-native";
</code>```

One reason for the analytics not showing up is if you had to change the APP_ID or APP_NAME for some reason. To fix this, remove and install "cordova-plugin-facebook4" using

```<code>ionic plugin remove cordova-plugin-facebook4 --save
</code>```

and reinstall using with the new values

```<code>ionic plugin add cordova-plugin-facebook4 --variable APP_ID="new_app_id" --variable APP_NAME="myApplication"
</code>```

Body:
I'm using ionic with plugin cordova-plugin-facebook4.
When I try to use logEvent() I didn't receive any error and also didn't get the information to my Facebook analytics.

I used logEvent() in the following way:

facebookConnectPlugin.logEvent('my event name', {}, 1);

Body:
Using arbitrary Strings as Event names are allowed. For e.g.

Facebook.logEvent('InvoicePage', {}, 1).then(function (value) {console.log('fulfilled logevent'); }, function (reason) {console.log('failed logevent'); });;

where Facebook is referred from :

import {Facebook} from "ionic-native";

One reason for the analytics not showing up is if you had to change the APP_ID or APP_NAME for some reason. To fix this, remove and install "cordova-plugin-facebook4" using

ionic plugin remove cordova-plugin-facebook4 --save

and reinstall using with the new values

ionic plugin add cordova-plugin-facebook4 --variable APP_ID="new_app_id" --variable APP_NAME="myApplication"


问:
Is long polling possible in Google App Engine?
I need to make application that needs to poll server often, but GAE has limitations on requests, so making a lot of requests could be very costly. Is it possible to use long polling and make requests wait for the maxium 30 seconds for changes?</p>

答:
We've tried implementing a Comet-like long-polling solution on App Engine, with mixed results.

```<code>def wait_for_update(request, blob):
    """
    Wait for blob update, if wait option specified in query string.
    Otherwise, return 304 Not Modified.
    """
    wait = request.GET.get('wait', '')
    if not wait.isdigit():
        return blob
    start = time.time()
    deadline = start + int(wait)
    original_sha1 = blob.sha1
    try:
        while time.time() < deadline:
            # Sleep one or two seconds.
            elapsed = time.time() - start
            time.sleep(1 if elapsed < 7 else 2)
            # Try to read updated blob from memcache.
            logging.info("Checking memcache for blob update after %.1fs",
                         elapsed)
            blob = Blob.cache_get_by_key_name(request.key_name)
            # Detect changes.
            if blob is None or blob.sha1 != original_sha1:
                break
    except DeadlineExceededError:
        logging.info("Caught DeadlineExceededError after %.1fs",
                     time.time() - start)
    return blob
</code>```

The problem I'm seeing is that requests following a long-polling one, are getting serialize (synchronized) behind the long-polling request.  I can look at a trace in Chrome and see a timeline like this:

Request 1 sent. GET (un-modified) blob (wait until changed).

Request 2 sent. Modify the blob.

After full time-out, Request 1 returns (data unmodified).

Request 2 gets processed on server, and returns success.

I've used wireshark and Chrome/timeline to confirm that I AM sending the modification request to the server on a distinct TCP connection from the long-polling one.  So this snychronization must be happing on the App Engine production server.  Google doesn't document this detail of the server behavior, as far as I know.

I think waiting for the channel API is the best hope we have of getting good real-time behavior from App Engine.

Body:
We've tried implementing a Comet-like long-polling solution on App Engine, with mixed results.

def wait_for_update(request, blob):
    """
    Wait for blob update, if wait option specified in query string.
    Otherwise, return 304 Not Modified.
    """
    wait = request.GET.get('wait', '')
    if not wait.isdigit():
        return blob
    start = time.time()
    deadline = start + int(wait)
    original_sha1 = blob.sha1
    try:
        while time.time() < deadline:
            # Sleep one or two seconds.
            elapsed = time.time() - start
            time.sleep(1 if elapsed < 7 else 2)
            # Try to read updated blob from memcache.
            logging.info("Checking memcache for blob update after %.1fs",
                         elapsed)
            blob = Blob.cache_get_by_key_name(request.key_name)
            # Detect changes.
            if blob is None or blob.sha1 != original_sha1:
                break
    except DeadlineExceededError:
        logging.info("Caught DeadlineExceededError after %.1fs",
                     time.time() - start)
    return blob

The problem I'm seeing is that requests following a long-polling one, are getting serialize (synchronized) behind the long-polling request.  I can look at a trace in Chrome and see a timeline like this:

Request 1 sent. GET (un-modified) blob (wait until changed).

Request 2 sent. Modify the blob.

After full time-out, Request 1 returns (data unmodified).

Request 2 gets processed on server, and returns success.

I've used wireshark and Chrome/timeline to confirm that I AM sending the modification request to the server on a distinct TCP connection from the long-polling one.  So this snychronization must be happing on the App Engine production server.  Google doesn't document this detail of the server behavior, as far as I know.

I think waiting for the channel API is the best hope we have of getting good real-time behavior from App Engine.


问:
How Caused by: java.lang.ClassNotFoundException:com.google.common.base.function will be handled in selenium?
Caused by: java.lang.ClassNotFoundException:com.google.common.base.function will be handled in selenium

got this error when running through Webdriver.

```<code>public class Logintoaccount {

    @Before
    public void setUp() throws Exception {
    System.setProperty("webdriver.ie.driver", "d:\\IEDriverServer.exe");
    WebDriver driver = new InternetExplorerDriver();

    }

    @Test
    public void test() {
        //System.setProperty("webdriver.chrome.driver", "d://chromedriver.exe");
    }
}
</code>```

答: Add selenium-server-standalone-version.jar file in the project. the issue will be resolved

Body:
Caused by: java.lang.ClassNotFoundException:com.google.common.base.function will be handled in selenium

got this error when running through Webdriver.

public class Logintoaccount {

    @Before
    public void setUp() throws Exception {
    System.setProperty("webdriver.ie.driver", "d:\\IEDriverServer.exe");
    WebDriver driver = new InternetExplorerDriver();

    }

    @Test
    public void test() {
        //System.setProperty("webdriver.chrome.driver", "d://chromedriver.exe");
    }
}


问:
How can I slice a list to get every 2 consecutive elements of the list in new lists?
Say you have a list [1,2,3,...,99,100]

```<code>import numpy as np
ls = np.linspace(1,100,100)
</code>```

Say you fiddle around with the slice notation to find ones that works for you.

```<code>print(ls[:2])
>> [ 1.  2.]

print(ls[::2])
>> [  1.   3.   5.   7.  ...  97.  99.]
</code>```

How can I slice the data in such a way that I can get

```<code>[1,2],[3,4],[5,6],[7,8],...,[99,100]
</code>```

## perhaps not important but my purpose is to adapt this to my dataset, where the values in the lists denote the numerical subscript of another list of values (other_values[index]) that are to be compared. Is it possible to combine slicing with arrays?

Body:
Say you have a list [1,2,3,...,99,100]

import numpy as np
ls = np.linspace(1,100,100)

Say you fiddle around with the slice notation to find ones that works for you.

print(ls[:2])
>> [ 1.  2.]

print(ls[::2])
>> [  1.   3.   5.   7.  ...  97.  99.]

How can I slice the data in such a way that I can get

[1,2],[3,4],[5,6],[7,8],...,[99,100]

## perhaps not important but my purpose is to adapt this to my dataset, where the values in the lists denote the numerical subscript of another list of values (other_values[index]) that are to be compared. Is it possible to combine slicing with arrays?

Body:
You can use the .resize(..,2) option for that. The result is that ls is now a numpy array with 50×2 dimensions:

>>> ls.resize(ls.shape[0]/2,2)
>>> ls
array([[   1.,    2.],
       [   3.,    4.],
       [   5.,    6.],
       [   7.,    8.],
       [   9.,   10.],
       [  11.,   12.],
       [  13.,   14.],
       [  15.,   16.],
       [  17.,   18.],
       [  19.,   20.],
       [  21.,   22.],
       [  23.,   24.],
       [  25.,   26.],
       [  27.,   28.],
       [  29.,   30.],
       [  31.,   32.],
       [  33.,   34.],
       [  35.,   36.],
       [  37.,   38.],
       [  39.,   40.],
       [  41.,   42.],
       [  43.,   44.],
       [  45.,   46.],
       [  47.,   48.],
       [  49.,   50.],
       [  51.,   52.],
       [  53.,   54.],
       [  55.,   56.],
       [  57.,   58.],
       [  59.,   60.],
       [  61.,   62.],
       [  63.,   64.],
       [  65.,   66.],
       [  67.,   68.],
       [  69.,   70.],
       [  71.,   72.],
       [  73.,   74.],
       [  75.,   76.],
       [  77.,   78.],
       [  79.,   80.],
       [  81.,   82.],
       [  83.,   84.],
       [  85.,   86.],
       [  87.,   88.],
       [  89.,   90.],
       [  91.,   92.],
       [  93.,   94.],
       [  95.,   96.],
       [  97.,   98.],
       [  99.,  100.]])


问:
Unable to push to github: repository not found
Whenever I try to push changes to a remote github repository from the command-line, I receive the following error:

```<code>> git push
remote: Repository not found.
fatal: repository 'https://github.com/MyOrg/MyRepo.git' not found
</code>```

(I've replaced org and repo name, but they are definitely the correct names).

I have checked I have write access to the repository. I'm able to create branches and write to files through the github website, and pull these changes back down locally.

I am authenticating with github using the Git Credential Manager for Windows (GCM), and I have the following in gitconfig:

```<code>[credential]
    helper = manager
</code>```

I'm running on Windows 10, git version 2.10.2.windows.1.

答: have you tried using the command suggest by SvinSimpe when you first cd into the directory where the branch is locally stored?

Body:
Whenever I try to push changes to a remote github repository from the command-line, I receive the following error:

> git push
remote: Repository not found.
fatal: repository 'https://github.com/MyOrg/MyRepo.git' not found

(I've replaced org and repo name, but they are definitely the correct names).

I have checked I have write access to the repository. I'm able to create branches and write to files through the github website, and pull these changes back down locally.

I am authenticating with github using the Git Credential Manager for Windows (GCM), and I have the following in gitconfig:

[credential]
    helper = manager

I'm running on Windows 10, git version 2.10.2.windows.1.


问:
How to write a query to get a row data between two dates using codeigniter active records?
I have below table with date format.

How can I write a query to fetch the records between two dates?

The code I have tried is given below:

```<code>$this->db->where(array('addeddate >=' => '2017-03-02');
$this->db->where(array('addeddate <=' =>'2017-03-28'));
$this->db->select("sales_commission.*");
$this->db->get("sales_commission");
</code>```

答:
No need to pass as array. use $this->db->where() like below. The result_array() is used to print data in array format.

```<code>$this->db->where('addeddate >=','2017-03-02');
$this->db->where('addeddate <=','2017-03-28');
$this->db->select("*");
$data = $this->db->get("sales_commission");
print_r($data->result_array());//prints records between matched dates
</code>```

Body:
I have below table with date format.

How can I write a query to fetch the records between two dates?

The code I have tried is given below:

$this->db->where(array('addeddate >=' => '2017-03-02');
$this->db->where(array('addeddate <=' =>'2017-03-28'));
$this->db->select("sales_commission.*");
$this->db->get("sales_commission");

Body:
No need to pass as array. use $this->db->where() like below. The result_array() is used to print data in array format.

$this->db->where('addeddate >=','2017-03-02');
$this->db->where('addeddate <=','2017-03-28');
$this->db->select("*");
$data = $this->db->get("sales_commission");
print_r($data->result_array());//prints records between matched dates


问:
How to use autocomplete in saltstack
I want to use bash autocomplete feature with saltstack.

salt '*' test.p <tab> should complete the word and make it salt '*' test.ping.

After googling, I got the following links:
salt.bash
& CLI completion

However, I cannot figure out how to use it. Autocompletion feature is not working by default. Please provide any step by step guide to activate it.

答:
Download the salt.bash file.

```<code> wget https://raw.githubusercontent.com/saltstack/salt/develop/pkg/salt.bash
</code>```

Copy the file to /etc/bash_completion.d/

```<code> cp salt.bash /etc/bash_completion.d/
</code>```

Logout and logback in. or source the file

```<code> source /etc/bash_completion.d/salt.bash
</code>```

Now use salt auto-completion feature

```<code> salt '*' tes[[tab]].pi[[tab]]
</code>```

and get the result:

```<code> salt '*' test.ping
</code>```

Title: How to use autocomplete in saltstack

Body:
Download the salt.bash file.

 wget https://raw.githubusercontent.com/saltstack/salt/develop/pkg/salt.bash

Copy the file to /etc/bash_completion.d/

 cp salt.bash /etc/bash_completion.d/

Logout and logback in. or source the file

 source /etc/bash_completion.d/salt.bash

Now use salt auto-completion feature

 salt '*' tes[[tab]].pi[[tab]]

and get the result:

 salt '*' test.ping

ContentLicense: CC BY-SA 4.0


问:
Can't bind to 'ng-model' since it isn't a known property of 'input'
Start learning Angular 2 , for this error tried almost all links in stack-overflow but still , please help me understand why still produces error even after import FormsModule

This is my customer.ts file

```<code>export class Customer {

  public CustomerName: string = "asdsad";
  public Code: string = "asdsa";
  public Amount: string = "asdasd";
}
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';

import { Customer } from "./Customer"

@Component({
selector: 'my-app',
moduleId: module.id,
templateUrl: './st.html'
})

   export class AppComponent {
customerobj: Customer = new Customer();
   }
</code>```

app.module.ts

```<code>            import { NgModule } from "@angular/core"
            import { BrowserModule } from "@angular/platform-browser"
            import { FormsModule } from '@angular/forms';
            import { AppComponent } from "./app.component"
            @NgModule({
                imports: [BrowserModule, FormsModule ],
                declarations: [AppComponent],
                bootstrap: [AppComponent]
            })

            export class AppModule { }
</code>```

main.ts

```<code>    import { platformBrowserDynamic } from "@angular/platform-browser-dynamic"

    import { AppModule } from "./app.module"

    platformBrowserDynamic().bootstrapModule(AppModule);
</code>```

答:
I assume you are using ng-model instead of ngModel

Change it as ngModel.

Since you have not posted the component.html,

It should be,

```<code><input [ngModel]="custoermerObj.Code"></input>
</code>```

Body:
Start learning Angular 2 , for this error tried almost all links in stack-overflow but still , please help me understand why still produces error even after import FormsModule

This is my customer.ts file

export class Customer {

  public CustomerName: string = "asdsad";
  public Code: string = "asdsa";
  public Amount: string = "asdasd";
}

app.component.ts

import { Component } from '@angular/core';

import { Customer } from "./Customer"

@Component({
selector: 'my-app',
moduleId: module.id,
templateUrl: './st.html'
})

   export class AppComponent {
customerobj: Customer = new Customer();
   }

app.module.ts

            import { NgModule } from "@angular/core"
            import { BrowserModule } from "@angular/platform-browser"
            import { FormsModule } from '@angular/forms';
            import { AppComponent } from "./app.component"
            @NgModule({
                imports: [BrowserModule, FormsModule ],
                declarations: [AppComponent],
                bootstrap: [AppComponent]
            })

            export class AppModule { }

main.ts

    import { platformBrowserDynamic } from "@angular/platform-browser-dynamic"

    import { AppModule } from "./app.module"

    platformBrowserDynamic().bootstrapModule(AppModule);

Body:
I assume you are using ng-model instead of ngModel

Change it as ngModel.

Since you have not posted the component.html,

It should be,

<input [ngModel]="custoermerObj.Code"></input>


答:
something like

```<code>list(zip(l[::2], l[1::2]))
</code>```

returns a list of tuples with your desired pairing

Title: How can I slice a list to get every 2 consecutive elements of the list in new lists?

Body:
something like

list(zip(l[::2], l[1::2]))

returns a list of tuples with your desired pairing


问:
Python how to define a function that only accepts an integer input that can be used for multiple lines
I am trying to make a program that has a user input numbers into multiple different lines of code and I am trying to make it so that if the user inputs something other than a number the program will ask the user again to input the number correctly. I was trying to define a function that I could use for all of them but every time I run the program, it crashes. Any help would be much appreciated, thank you.

My code:

```<code>def error():
    global m1
    global m2
    global w1
    global w2
    while True:
        try:
            int(m1 or m2 or w1 or w2)
        except ValueError:
            try:
                float(m1 or m2 or w1 or w2)
            except ValueError:
                m1 or m2 or w1 or w2=input("please input your response correctly...")
                break

m1=input("\nWhat was your first marking period percentage?")
error()
w1=input("\nWhat is the weighting of the first marking period? (in decimal)")
error()
m2=input("\nWhat was your second marking period percentage?")
error()
w2=input("\nWhat is the weighting of the second marking period? (in decimal)")
error()
</code>```

答:
```<code>def user_input(msg):
    inp = input(msg)
    try:
        return int(inp) if inp.isnumeric() else float(inp)
    except ValueError as e:
        return user_input("Please enter a numeric value")

m1=user_input("\nWhat was your first marking period percentage?")
w1=user_input("\nWhat is the weighting of the first marking period? (in decimal)")
m2=user_input("\nWhat was your second marking period percentage?")
w2=user_input("\nWhat is the weighting of the second marking period? (in decimal)")
</code>```

Body:
I am trying to make a program that has a user input numbers into multiple different lines of code and I am trying to make it so that if the user inputs something other than a number the program will ask the user again to input the number correctly. I was trying to define a function that I could use for all of them but every time I run the program, it crashes. Any help would be much appreciated, thank you.

My code:

def error():
    global m1
    global m2
    global w1
    global w2
    while True:
        try:
            int(m1 or m2 or w1 or w2)
        except ValueError:
            try:
                float(m1 or m2 or w1 or w2)
            except ValueError:
                m1 or m2 or w1 or w2=input("please input your response correctly...")
                break

m1=input("\nWhat was your first marking period percentage?")
error()
w1=input("\nWhat is the weighting of the first marking period? (in decimal)")
error()
m2=input("\nWhat was your second marking period percentage?")
error()
w2=input("\nWhat is the weighting of the second marking period? (in decimal)")
error()


问:
Sqlite how to create table with Foreign key
So I have searched a few questions on this topic, but I have realized that those questions are more related to whether or not you are allowed to create tables with no PKs etc. My problem is that the following code generates a an error: E/SQLiteLog: (1) near "FOREIGN": syntax error

Code:

```<code>CREATE TABLE tblPart(PartNumber [nvarchar](15) PRIMARY KEY NOT NULL,
PartDescription [nvarchar](150) NOT NULL);

CREATE TABLE tblStock(PartNumber [nvarchar](15) FOREIGN KEY REFERENCES
tblPart(PartNumber) ON DELETE CASCADE ON UPDATE CASCADE NOT NULL,
StockOH [int] NOT NULL);
</code>```

Executing this code in MSSQLSERVER works perfectly, but when ran in Java/Android using SQLite it generates said error.

Thank you in advance for your assistance.

EDIT:

DataHandler Class:

```<code>public myDAL(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
{
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    //region create tblPart
    sbCreatePart.append("CREATE TABLE " + TABLE_PART + "(");
    sbCreatePart.append(COLUMN_PART_PARTNR + " [nvarchar](15) PRIMARY KEY NOT NULL, ");
    sbCreatePart.append(COLUMN_PART_DESCRIPTION + " [nvarchar](150) NOT NULL)");
    //endregion

    //region create tblCurrentStock
    sbCreateCurrStock.append("CREATE TABLE " + TABLE_CURRENTSTOCK + "(");
    sbCreateCurrStock.append(COLUMN_CURRENTSTOCK_PARTNR + " [nvarchar](15) FOREIGN KEY REFERENCES "
        + TABLE_PART + "(" + COLUMN_PART_PARTNR + ") ON DELETE CASCADE ON UPDATE CASCADE NOT NULL, ");
    sbCreateCurrStock.append(COLUMN_CURRENTSTOCK_STOCKOH + " [int] NOT NULL)");
    //endregion
    db.execSQL(sbCreatePart.toString());
    Log.d("Test", "tblPart");
    db.execSQL(sbCreateCurrStock.toString());
    Log.d("Test", "tblCurrStock");
}

public boolean TestInsert()
{
    boolean result = true;
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();

    try
    {
        values.put(COLUMN_PART_PARTNR, "PNTest123");
        values.put(COLUMN_PART_DESCRIPTION, "Dummy Test Part");
        Log.d("Test Input", "Values Added");
        db.insert(TABLE_PART, null, values);
        Log.d("Test Input", "Insert Successful");
    }
    catch (Exception ex)
    {
        result = false;
    }
    finally
    {
        db.close();
    }
    return result;
}
</code>```

Activity Class:

```<code>public void onPartsClick(View v)
{
    myDAL dal = new myDAL(this, null, null, 1);
    boolean x = dal.TestInsert();
    if(x)
        Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
}
</code>```

答:
You have syntax error try this:

```<code>CREATE TABLE tblPart(PartNumber nvarchar(15) PRIMARY KEY NOT NULL,
PartDescription nvarchar(150) NOT NULL);

CREATE TABLE tblStock(PartNumber nvarchar(15)  REFERENCES
tblPart(PartNumber) ON DELETE CASCADE ON UPDATE CASCADE NOT NULL,
StockOH integer NOT NULL);
</code>```

You dont need FOREIGN KEY if you putting the foreign key definition on the column definition.

OR try it like this:

```<code>CREATE TABLE tblStock10(PartNumber nvarchar(15),
StockOH integer NOT NULL,
FOREIGN KEY (PartNumber) REFERENCES tblPart1(PartNumber)
  ON UPDATE SET NULL);
</code>```

Body:
So I have searched a few questions on this topic, but I have realized that those questions are more related to whether or not you are allowed to create tables with no PKs etc. My problem is that the following code generates a an error: E/SQLiteLog: (1) near "FOREIGN": syntax error

Code:

CREATE TABLE tblPart(PartNumber [nvarchar](15) PRIMARY KEY NOT NULL,
PartDescription [nvarchar](150) NOT NULL);

CREATE TABLE tblStock(PartNumber [nvarchar](15) FOREIGN KEY REFERENCES
tblPart(PartNumber) ON DELETE CASCADE ON UPDATE CASCADE NOT NULL,
StockOH [int] NOT NULL);

Executing this code in MSSQLSERVER works perfectly, but when ran in Java/Android using SQLite it generates said error.

Thank you in advance for your assistance.

EDIT:

DataHandler Class:

public myDAL(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
{
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    //region create tblPart
    sbCreatePart.append("CREATE TABLE " + TABLE_PART + "(");
    sbCreatePart.append(COLUMN_PART_PARTNR + " [nvarchar](15) PRIMARY KEY NOT NULL, ");
    sbCreatePart.append(COLUMN_PART_DESCRIPTION + " [nvarchar](150) NOT NULL)");
    //endregion

    //region create tblCurrentStock
    sbCreateCurrStock.append("CREATE TABLE " + TABLE_CURRENTSTOCK + "(");
    sbCreateCurrStock.append(COLUMN_CURRENTSTOCK_PARTNR + " [nvarchar](15) FOREIGN KEY REFERENCES "
        + TABLE_PART + "(" + COLUMN_PART_PARTNR + ") ON DELETE CASCADE ON UPDATE CASCADE NOT NULL, ");
    sbCreateCurrStock.append(COLUMN_CURRENTSTOCK_STOCKOH + " [int] NOT NULL)");
    //endregion
    db.execSQL(sbCreatePart.toString());
    Log.d("Test", "tblPart");
    db.execSQL(sbCreateCurrStock.toString());
    Log.d("Test", "tblCurrStock");
}

public boolean TestInsert()
{
    boolean result = true;
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();

    try
    {
        values.put(COLUMN_PART_PARTNR, "PNTest123");
        values.put(COLUMN_PART_DESCRIPTION, "Dummy Test Part");
        Log.d("Test Input", "Values Added");
        db.insert(TABLE_PART, null, values);
        Log.d("Test Input", "Insert Successful");
    }
    catch (Exception ex)
    {
        result = false;
    }
    finally
    {
        db.close();
    }
    return result;
}

Activity Class:

public void onPartsClick(View v)
{
    myDAL dal = new myDAL(this, null, null, 1);
    boolean x = dal.TestInsert();
    if(x)
        Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
}

Body:
You have syntax error try this:

CREATE TABLE tblPart(PartNumber nvarchar(15) PRIMARY KEY NOT NULL,
PartDescription nvarchar(150) NOT NULL);

CREATE TABLE tblStock(PartNumber nvarchar(15)  REFERENCES
tblPart(PartNumber) ON DELETE CASCADE ON UPDATE CASCADE NOT NULL,
StockOH integer NOT NULL);

You dont need FOREIGN KEY if you putting the foreign key definition on the column definition.

OR try it like this:

CREATE TABLE tblStock10(PartNumber nvarchar(15),
StockOH integer NOT NULL,
FOREIGN KEY (PartNumber) REFERENCES tblPart1(PartNumber)
  ON UPDATE SET NULL);


问:
ExtJS 6 plugin.rowwidget Get binded record upon row body component creation
I have a grid with Ext.grid.plugin.RowWidget. When I expand row I have to load some data via ajax using row record data as request parameters and display loaded data in a row body component.

How I can get row record data upon row body component creation? I've tried initComponent and afterrender listener, but I understand that it is not appropriate place because data is not binded yet. I have to listen for another event or?

Here is simple fiddle illustrating my problem and what I've tried already.

答:
Thanks to Evan Trimboli, onWidgetAttach seems to work:

```<code>        plugins: [{
            ptype: 'rowwidget',
            widget: {
                xtype: 'characterPanel',
                bind: {
                    characterName: '{record.name}'
                },
            },
            onWidgetAttach: function (plugin, bodyComponent, record) {
                // Do stuff
            }
        }],
</code>```

Check updated fiddle.

Body:
Thanks to Evan Trimboli, onWidgetAttach seems to work:

        plugins: [{
            ptype: 'rowwidget',
            widget: {
                xtype: 'characterPanel',
                bind: {
                    characterName: '{record.name}'
                },
            },
            onWidgetAttach: function (plugin, bodyComponent, record) {
                // Do stuff
            }
        }],

Check updated fiddle.


问:
Check if column value is in other columns in pandas
I have the following dataframe in pandas

```<code>  target   A       B      C
0 cat      bridge  cat    brush
1 brush    dog     cat    shoe
2 bridge   cat     shoe   bridge
</code>```

How do I test whether df.target is in any of the columns ['A','B','C', etc.], where there are many columns to check?

I have tried merging A,B and C into a string to use df.abcstring.str.contains(df.target) but this does not work.

答:
you can use apply a function for each row that counts the number of value that match the value in the 'target' column:

```<code>df["exist"] = df.apply(lambda row:row.value_counts()[row['target']] > 1 , axis=1)
</code>```

for a dataframe that looks like:

```<code>   b  c target
0  3  a      a
1  3  4      2
2  3  4      2
3  3  4      2
4  3  4      4
</code>```

the output will be:

```<code>   b  c target  exist
0  3  a      a   True
1  3  4      2  False
2  3  4      2  False
3  3  4      2  False
4  3  4      4   True
</code>```

Body:
I have the following dataframe in pandas

  target   A       B      C
0 cat      bridge  cat    brush
1 brush    dog     cat    shoe
2 bridge   cat     shoe   bridge

How do I test whether df.target is in any of the columns ['A','B','C', etc.], where there are many columns to check?

I have tried merging A,B and C into a string to use df.abcstring.str.contains(df.target) but this does not work.

Body:
you can use apply a function for each row that counts the number of value that match the value in the 'target' column:

df["exist"] = df.apply(lambda row:row.value_counts()[row['target']] > 1 , axis=1)

for a dataframe that looks like:

   b  c target
0  3  a      a
1  3  4      2
2  3  4      2
3  3  4      2
4  3  4      4

the output will be:

   b  c target  exist
0  3  a      a   True
1  3  4      2  False
2  3  4      2  False
3  3  4      2  False
4  3  4      4   True


问:
methodObject notation in javascript libraries (e.g. React and Sequelize)
In Sequelize there is a method to create a database entry with a relation to a model, for example:

```<code>user.createPost({...})
</code>```

Which amounts to instance.methodInstance. I thought that the "createPost" notation was some peculiarity of Sequelize, but than I ran into React. In React you can define a component like such:

```<code>function Square(props) {
      return (
        <button className="square" onClick={() => props.onClick()} >
          {props.value}
        </button>
       );
    }
</code>```

Another component can render that like this:

```<code>class Board extends React.Component {
  renderSquare(i) {
    return <Square />;
  }
</code>```

Now we have the "renderSquare" notation, which amounts to methodClass. Is this some java syntax I'm not aware of, or is it a coincidence that these two libraries have a similar style?

So I'm asking if writing a method and an object concatenated in camel case instead of the (more usual) object.method syntax is standard javascript syntax.

答:
JavaScript has been evolving ridiculously quick - to a point where things can get a bit confusing.
Before ES6 there was no class keyword in JS. But you could achieve the same results by creating a function and attaching methods to it via the prototype.

A LOT of developers, especially the ones used to Java/C#, couldn't understand the prototype. ES6 created some syntax sugar to declare classes the old school OOP style - that's why the second example looks "java-esque". And I gotta admit - I actually love the new syntax. So much clearer.

So, that's all there is to it - you can actually use whatever approach you prefer. Just bear in mind that, with react, a component that's basically a single function (not a constructor) is supposed to be stateless and implement minimal logic - the kind of component that basically only renders something simple. For anything a bit more complex, you should use a stateful component - using either ES6 classes or regular ES5 with React.createClass.

There's a good guide here that explains most of what you need to know when it comes to ES6 vs ES5 React code:
https://facebook.github.io/react/docs/react-without-es6.html

Body:
In Sequelize there is a method to create a database entry with a relation to a model, for example:

user.createPost({...})

Which amounts to instance.methodInstance. I thought that the "createPost" notation was some peculiarity of Sequelize, but than I ran into React. In React you can define a component like such:

function Square(props) {
      return (
        <button className="square" onClick={() => props.onClick()} >
          {props.value}
        </button>
       );
    }

Another component can render that like this:

class Board extends React.Component {
  renderSquare(i) {
    return <Square />;
  }

Now we have the "renderSquare" notation, which amounts to methodClass. Is this some java syntax I'm not aware of, or is it a coincidence that these two libraries have a similar style?

So I'm asking if writing a method and an object concatenated in camel case instead of the (more usual) object.method syntax is standard javascript syntax.


问:
How to go back to Previous Activity?
Someone ask me a question a week ago and till now i did not get the answer of that question.The question was how we can go back to previous Activity by pressing back button of device without using intent or finish(). </p>

答:
You can do it by simply overriding onBackPressed method in your activity.

```<code>  @Override
    public void onBackPressed() {
        super.onBackPressed();
    }
</code>```

Hope this help!

Title: How to go back to Previous Activity?

Body:
You can do it by simply overriding onBackPressed method in your activity.

  @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

Hope this help!


答:
You must have used "ng-model" inside input tag

For Angular2/4 use ngModel

ng-model is For angular 1

ngModel is For angular 2

Title: Can't bind to 'ng-model' since it isn't a known property of 'input'


答:
Use DATE(addeddate) in where clause

For Check date condition Use DATE()  For DATETIME Type Column

Try below script

```<code>$this->db->select("*");
$this->db->from("sales_commission");
$this->db->where('DATE(addeddate) >=','2017-03-02');
$this->db->where('DATE(addeddate) <=','2017-03-28');
$query = $this->db->get();
if($query->num_rows() > 0){
echo "```";
print_r($query->result());
}else{
echo "No records found!";
}
```

Title: How to write a query to get a row data between two dates using codeigniter active records?

Body:
Use DATE(addeddate) in where clause

For Check date condition Use DATE()  For DATETIME Type Column

Try below script

$this->db->select("*");
$this->db->from("sales_commission");
$this->db->where('DATE(addeddate) >=','2017-03-02');
$this->db->where('DATE(addeddate) <=','2017-03-28');
$query = $this->db->get();
if($query->num_rows() > 0){
echo "<pre>";
print_r($query->result());
}else{
echo "No records found!";
}