问:
Enumerable.Repeat for reference type objects initialization
I have a question about Enumerable.Repeat function.

If I will have a class:

```<code>class A
{
//code
}
</code>```

And I will create an array, of that type objects:

```<code>A [] arr = new A[50];
</code>```

And next, I will want to initialize those objects, calling Enumerable.Repeat:

```<code>arr = Enumerable.Repeat(new A(), 50);
</code>```

Will those objects have the same address in memory?
If I will want to check their hash code, for example in that way:

```<code>bool theSameHashCode = questions[0].GetHashCode() == questions[1].GetHashCode();
</code>```

This will return me true, and if I will change one object properties, all other objects will change it too.

So my question is: is that properly way, to initialize reference type objects? If not, then what is a better way?

答:
Using Enumerable.Repeat this way will initialize only one object and return that object every time when you iterate over the result.

Will those objects have the same address in memory?

There is only one object.

To achieve what you want, you can do this:

```<code>Enumerable.Range(1, 50).Select(i => new A()).ToArray();
</code>```

This will return an array of 50 distinct objects of type A.

By the way, the fact that GetHashCode() returns the same value does not imply that the objects are referentially equal (or simply equal, for that matter). Two non-equal objects can have the same hash code.

Body:
I have a question about Enumerable.Repeat function.

If I will have a class:

class A
{
//code
}

And I will create an array, of that type objects:

A [] arr = new A[50];

And next, I will want to initialize those objects, calling Enumerable.Repeat:

arr = Enumerable.Repeat(new A(), 50);

Will those objects have the same address in memory?
If I will want to check their hash code, for example in that way:

bool theSameHashCode = questions[0].GetHashCode() == questions[1].GetHashCode();

This will return me true, and if I will change one object properties, all other objects will change it too.

So my question is: is that properly way, to initialize reference type objects? If not, then what is a better way?

Body:
Using Enumerable.Repeat this way will initialize only one object and return that object every time when you iterate over the result.

Will those objects have the same address in memory?

There is only one object.

To achieve what you want, you can do this:

Enumerable.Range(1, 50).Select(i => new A()).ToArray();

This will return an array of 50 distinct objects of type A.

By the way, the fact that GetHashCode() returns the same value does not imply that the objects are referentially equal (or simply equal, for that matter). Two non-equal objects can have the same hash code.


来源: stackexchange

问:
Why is RMSProp considered "leaky"?
```<code>decay_rate = 0.99 # decay factor for RMSProp leaky sum of grad^2
</code>```

I'm perplexed by the wording of comments like the above where they talk about a "leaky" sum of squares for the RMSProp optimizer. So far I've been able to uncover that this particular line is copy-pasta'd from Andrej Karpathy's Deep Reinforcement Learning: Pong from Pixels, and that RMSProp is an unpublished optimizer proposed by Hinton in one of his Coursera Classes. Looking at the math for RMSProp from link 2, it's hard to figure out how any of this is "leaky."

Would anyone happen to know why RMSProp is described this way?

答:
RMsprop keeps the exponentialy decaying average of squared gradients. Wording (however unfortunate) of "leaky" refers to the fact how much of the previous estimate "leaks" to the current one, since</p>

```<code>E[g^2]_t := 0.99 E[g^2]_{t-1} + 0.01 g^2_t
            \_______________/   \________/
               "leaking"         new data
</code>```

ContentLicense: CC BY-SA 3.0

Title: Why is RMSProp considered "leaky"?

Body:
decay_rate = 0.99 # decay factor for RMSProp leaky sum of grad^2

I'm perplexed by the wording of comments like the above where they talk about a "leaky" sum of squares for the RMSProp optimizer. So far I've been able to uncover that this particular line is copy-pasta'd from Andrej Karpathy's Deep Reinforcement Learning: Pong from Pixels, and that RMSProp is an unpublished optimizer proposed by Hinton in one of his Coursera Classes. Looking at the math for RMSProp from link 2, it's hard to figure out how any of this is "leaky."

Would anyone happen to know why RMSProp is described this way?

Body:
RMsprop keeps the exponentialy decaying average of squared gradients. Wording (however unfortunate) of "leaky" refers to the fact how much of the previous estimate "leaks" to the current one, since

E[g^2]_t := 0.99 E[g^2]_{t-1} + 0.01 g^2_t
            \_______________/   \________/
               "leaking"         new data


问:
Fit image into ImageView, keep aspect ratio and then resize ImageView to image dimensions?
How to fit an image of random size to an ImageView?

When:

Initially ImageView dimensions are 250dp *  250dp

The image's larger dimension should be scaled up/down to 250dp

The image should keep its aspect ratio

The ImageView dimensions should match scaled image's dimensions after scaling

E.g. for an image of 100*150, the image and the ImageView should be 166*250.

E.g. for an image of 150*100, the image and the ImageView should be 250*166.

If I set the bounds as

```<code><ImageView
    android:id="@+id/picture"
    android:layout_width="250dp"
    android:layout_height="250dp"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="20dp"
    android:adjustViewBounds="true" />
</code>```

images fit properly in the ImageView, but the ImageView is always 250dp * 250dp.

答:
I needed to get this done in a constraint layout with Picasso, so I munged together some of the above answers and came up with this solution (I already know the aspect ratio of the image I'm loading, so that helps):

Called in my activity code somewhere after setContentView(...)

```<code>protected void setBoxshotBackgroundImage() {
    ImageView backgroundImageView = (ImageView) findViewById(R.id.background_image_view);

    if(backgroundImageView != null) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int width = displayMetrics.widthPixels;
        int height = (int) Math.round(width * ImageLoader.BOXART_HEIGHT_ASPECT_RATIO);

        // we adjust the height of this element, as the width is already pinned to the parent in xml
        backgroundImageView.getLayoutParams().height = height;

        // implement your Picasso loading code here
    } else {
        // fallback if no element in layout...
    }
}
</code>```

In my XML

```<code><?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteY="0dp"
tools:layout_editor_absoluteX="0dp">

    <ImageView
        android:id="@+id/background_image_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:scaleType="fitStart"
        app:srcCompat="@color/background"
        android:adjustViewBounds="true"
        tools:layout_editor_absoluteY="0dp"
        android:layout_marginTop="0dp"
        android:layout_marginBottom="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginLeft="0dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <!-- other elements of this layout here... -->

</android.support.constraint.ConstraintLayout>
</code>```

Note the lack of a constraintBottom_toBottomOf attribute. ImageLoader is my own static class for image loading util methods and constants.

Body:
How to fit an image of random size to an ImageView?

When:

Initially ImageView dimensions are 250dp *  250dp

The image's larger dimension should be scaled up/down to 250dp

The image should keep its aspect ratio

The ImageView dimensions should match scaled image's dimensions after scaling

E.g. for an image of 100*150, the image and the ImageView should be 166*250.

E.g. for an image of 150*100, the image and the ImageView should be 250*166.

If I set the bounds as

<ImageView
    android:id="@+id/picture"
    android:layout_width="250dp"
    android:layout_height="250dp"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="20dp"
    android:adjustViewBounds="true" />

images fit properly in the ImageView, but the ImageView is always 250dp * 250dp.

Body:
I needed to get this done in a constraint layout with Picasso, so I munged together some of the above answers and came up with this solution (I already know the aspect ratio of the image I'm loading, so that helps):

Called in my activity code somewhere after setContentView(...)

protected void setBoxshotBackgroundImage() {
    ImageView backgroundImageView = (ImageView) findViewById(R.id.background_image_view);

    if(backgroundImageView != null) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int width = displayMetrics.widthPixels;
        int height = (int) Math.round(width * ImageLoader.BOXART_HEIGHT_ASPECT_RATIO);

        // we adjust the height of this element, as the width is already pinned to the parent in xml
        backgroundImageView.getLayoutParams().height = height;

        // implement your Picasso loading code here
    } else {
        // fallback if no element in layout...
    }
}

In my XML

<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteY="0dp"
tools:layout_editor_absoluteX="0dp">

    <ImageView
        android:id="@+id/background_image_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:scaleType="fitStart"
        app:srcCompat="@color/background"
        android:adjustViewBounds="true"
        tools:layout_editor_absoluteY="0dp"
        android:layout_marginTop="0dp"
        android:layout_marginBottom="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginLeft="0dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <!-- other elements of this layout here... -->

</android.support.constraint.ConstraintLayout>

Note the lack of a constraintBottom_toBottomOf attribute. ImageLoader is my own static class for image loading util methods and constants.


问:
if the file not exits then return no error vb
I have start this application every things its work fine but i have a small bug but i can not find the solution to solve the error.

i have debug it and the error its because the file not exist
is there any way to me to populate my datagridview with all *.gif images From a directory and the check if its null or some thing like that.
What i mean is is there any way to my to populate all gif images found on the chose Directory?
in fact i have all ready try like this but i get one error "Provided column already belongs to the DataGridView control.

```<code>Well finaly i have found a solution to load all images from a directory to a datagridview programmatic
</code>```

Here Is The Working Code

```<code>Public Class Form5

Private Sub addBtn_Click(sender As Object, e As EventArgs) Handles addBtn.Click
    'Populate()
    ShowImages()

End Sub
'CLEAR DATAGRIDVIEW
Private Sub clearBtn_Click(sender As Object, e As EventArgs) Handles clearBtn.Click
    DataGridView1.Rows.Clear()
End Sub
'WHEN AN IMAGE IS CLICKED
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
    MessageBox.Show("You Clicked Image At Col: " + e.ColumnIndex.ToString() + " Row: " + e.RowIndex.ToString())
End Sub

Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub

Public Sub ShowImages()

    Dim directory As New System.IO.DirectoryInfo("C:\avitogifconverter\")

    If directory.Exists Then

        Dim pngFiles() As System.IO.FileInfo = directory.GetFiles("*.gif")

        For Each pngFile As System.IO.FileInfo In pngFiles

            If pngFile.Exists Then

                Dim image = System.Drawing.Image.FromFile(pngFile.FullName)

                Using image
                    Dim count = 1
                    ' do something with the image like show in picture box
                    'CONSTRUCT IMG COLUMN
                    Dim imgCol As DataGridViewImageColumn = New DataGridViewImageColumn()
                    imgCol.HeaderText = "Photo"
                    imgCol.Name = "Col 1"
                    DataGridView1.Columns.Add(imgCol)
                    'CONSTRUCT ROWS
                    'FIRST ROW

                    Dim img As Image = System.Drawing.Image.FromFile(pngFile.FullName)

                    Dim row As Object() = New Object() {img, img, img}

                    DataGridView1.Rows.Add(row)
                End Using

            End If
        Next
    End If
End Sub
End Class
</code>```

答:
Using Directory.EnumerateFiles, you could do something like this:

```<code>Dim row = New List(Of Image)(3)
For Each filename In Directory.EnumerateFiles("C:\avitogifconverter", "*.gif")
    row.Add(Image.FromFile(filename))
    If row.Count = 3 Then
        DataGridView1.Rows.Add(row.ToArray())
        row.Clear()
    End If
Next
If row.Count > 0 Then
    DataGridView1.Rows.Add(row.ToArray())
    row.Clear()
End If
</code>```

Body:
I have start this application every things its work fine but i have a small bug but i can not find the solution to solve the error.

i have debug it and the error its because the file not exist
is there any way to me to populate my datagridview with all *.gif images From a directory and the check if its null or some thing like that.
What i mean is is there any way to my to populate all gif images found on the chose Directory?
in fact i have all ready try like this but i get one error "Provided column already belongs to the DataGridView control.

Well finaly i have found a solution to load all images from a directory to a datagridview programmatic

Here Is The Working Code

Public Class Form5

Private Sub addBtn_Click(sender As Object, e As EventArgs) Handles addBtn.Click
    'Populate()
    ShowImages()

End Sub
'CLEAR DATAGRIDVIEW
Private Sub clearBtn_Click(sender As Object, e As EventArgs) Handles clearBtn.Click
    DataGridView1.Rows.Clear()
End Sub
'WHEN AN IMAGE IS CLICKED
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
    MessageBox.Show("You Clicked Image At Col: " + e.ColumnIndex.ToString() + " Row: " + e.RowIndex.ToString())
End Sub

Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub

Public Sub ShowImages()

    Dim directory As New System.IO.DirectoryInfo("C:\avitogifconverter\")

    If directory.Exists Then

        Dim pngFiles() As System.IO.FileInfo = directory.GetFiles("*.gif")

        For Each pngFile As System.IO.FileInfo In pngFiles

            If pngFile.Exists Then

                Dim image = System.Drawing.Image.FromFile(pngFile.FullName)

                Using image
                    Dim count = 1
                    ' do something with the image like show in picture box
                    'CONSTRUCT IMG COLUMN
                    Dim imgCol As DataGridViewImageColumn = New DataGridViewImageColumn()
                    imgCol.HeaderText = "Photo"
                    imgCol.Name = "Col 1"
                    DataGridView1.Columns.Add(imgCol)
                    'CONSTRUCT ROWS
                    'FIRST ROW

                    Dim img As Image = System.Drawing.Image.FromFile(pngFile.FullName)

                    Dim row As Object() = New Object() {img, img, img}

                    DataGridView1.Rows.Add(row)
                End Using

            End If
        Next
    End If
End Sub
End Class

Body:
Using Directory.EnumerateFiles, you could do something like this:

Dim row = New List(Of Image)(3)
For Each filename In Directory.EnumerateFiles("C:\avitogifconverter", "*.gif")
    row.Add(Image.FromFile(filename))
    If row.Count = 3 Then
        DataGridView1.Rows.Add(row.ToArray())
        row.Clear()
    End If
Next
If row.Count > 0 Then
    DataGridView1.Rows.Add(row.ToArray())
    row.Clear()
End If


问:
Remove a specific item from a list by iterating
I want to remove specific items from python list by iterating and checking if it meet some requirements. At first, I just operate on a list of customized class objects, but it actually meet some errors, and I experiment on a python list of primitive type int, just to find strange result!

Here is some code excerpts:

```<code>>>> a=[1,2,3,4,5]
>>> for i in a:
...     a.remove(i)
...
>>> a
[2, 4]
</code>```

I expect the a should be [] after the loop, but it proves to be [2,4], I wonder why actually. I found a related question in Remove items from a list while iterating, but it only gives a solution on how to remove specific items, not concerning the mechanism actually. I really want to know the reason of this strange result.

答:
The reason your solution doesn't work as expected is because the iterator doesn't behave the way you'd expect if the list is modified. If you're example was rewritten this way, you'd get the result you expect.

```<code>>>> a=[1,2,3,4,5]
>>> b = a[:]
>>> for i in b:
...     a.remove(i)
...
>>> a
[]
</code>```

This is because 'b' is a copy of 'a', so be doesn't get modified when a does. This means the iterator doesn't have the data structure modified underneath it.

A more efficient solution is:

```<code>a = [1,2,3,4,5]
a = [i for i in a if not condition(i)]
</code>```

This list comprehension copies as it goes through the source list, and only bothers to copy the elements that aren't being removed.

Body:
I want to remove specific items from python list by iterating and checking if it meet some requirements. At first, I just operate on a list of customized class objects, but it actually meet some errors, and I experiment on a python list of primitive type int, just to find strange result!

Here is some code excerpts:

>>> a=[1,2,3,4,5]
>>> for i in a:
...     a.remove(i)
...
>>> a
[2, 4]

I expect the a should be [] after the loop, but it proves to be [2,4], I wonder why actually. I found a related question in Remove items from a list while iterating, but it only gives a solution on how to remove specific items, not concerning the mechanism actually. I really want to know the reason of this strange result.

Body:
The reason your solution doesn't work as expected is because the iterator doesn't behave the way you'd expect if the list is modified. If you're example was rewritten this way, you'd get the result you expect.

>>> a=[1,2,3,4,5]
>>> b = a[:]
>>> for i in b:
...     a.remove(i)
...
>>> a
[]

This is because 'b' is a copy of 'a', so be doesn't get modified when a does. This means the iterator doesn't have the data structure modified underneath it.

A more efficient solution is:

a = [1,2,3,4,5]
a = [i for i in a if not condition(i)]

This list comprehension copies as it goes through the source list, and only bothers to copy the elements that aren't being removed.


问:
Convert byte array to float in Lua [Float Data Structure]
I have the ability to read the memory with Lua, but I've run into a problem.
I want to read a float value.

I have, what I presume to be a float, in the memory which looks like this.

```<code>Byte Array 65 B6 40 43 EC 35 87 41 51 04 9E 3F
Float Value 192.712478637695
</code>```

I know the float value because I'm using a memory editor.
In Lua I have a function similar to memcpy, it's called readmem(Address,bytes) it returns an integer value.

How would I read the byte array into a float in Lua using readmem.

For the sake of this question I suppose you could assume that the 6 in 65 is address 00000000.

答:
string.pack

Passing 'f' as the first parameter will return a 4 byte string of the single precision representation, while 'd' will return an 8 byte string of the double precision representation. You can even declare the endianness of the float

ContentLicense: CC BY-SA 2.5

Body:
I have the ability to read the memory with Lua, but I've run into a problem.
I want to read a float value.

I have, what I presume to be a float, in the memory which looks like this.

Byte Array 65 B6 40 43 EC 35 87 41 51 04 9E 3F
Float Value 192.712478637695

I know the float value because I'm using a memory editor.
In Lua I have a function similar to memcpy, it's called readmem(Address,bytes) it returns an integer value.

How would I read the byte array into a float in Lua using readmem.

For the sake of this question I suppose you could assume that the 6 in 65 is address 00000000.


问:
Powershell - comparing lines
I need to parse through a file and when lines with the same connection-ID (655629, in this example) are found, compare them and only keep the one that is not 'other'

These two lines, for example:

```<code>08/26-20:26:42.655629  [**] [1:9000003:0] troll [**] [Priority: 0] {TCP} 192.168.0.1:35964 -> 192.168.0.99:368
08/26-20:26:42.655629  [**] [1:1:0] other [**] [Priority: 0] {TCP} 192.168.0.1:35964 -> 192.168.0.99:368
</code>```

Someone here was already kind enough to share this code, that basically returns the parts of each line that I need, formatted the way that I need.

```<code>Get-Content $logFile -ReadCount 1 | % {
'|' + (($_.Split()[0, 9, 11, 4] -replace ':', '|') -join '|') + '|'
} | Out-File "C:\Log\logout.txt"

|08/26-20|26|42.655629|192.168.0.1|35964|192.168.0.99|368|troll|
|08/26-20|26|42.655629|192.168.0.1|35964|192.168.0.99|368|other|
</code>```

However, I only want to keep one line when there are multiple lines with the same connection ID (655629 in this example). In cases when there are multiple lines with the same connection ID, I need the line that is NOT 'other'

I'm showing that first indice [0] only for comparison-sake. I need to remove it from the final output for all lines.

For example, final output should look something like this:

```<code>|192.168.0.1|35964|192.168.0.99|368|troll|
|192.168.0.254|35964|192.168.0.99|368|troll|
|192.168.0.9|35964|192.168.0.99|368|other|
|192.168.0.199|35964|192.168.0.99|368|troll|
|192.168.0.199|35964|192.168.0.99|368|other|
</code>```

Any help is much appreciated!

答:
If the last field that you want to remove is always going to be 'other', you could add a where-object filter to remove them.

```<code>Get-Content $logFile -ReadCount 1 | % {
'|' + (($_.Split()[0, 9, 11, 4] -replace ':', '|') -join '|') + '|'
} | where-object {$_ -notlike "*other|"} | Out-File "C:\Log\logout.txt"
</code>```

If 'other' is representative of something else, you could use a -UNIQUE option and see about filtering to only a single copy of each. Problem being you don't currently name the fields, which you could do via expressions..

```<code>(Get-Content $logFile -ReadCount 1 | select @{name="DateTime";Expression={$_.split(" ")[0].split(".")[0]}}, @{name="ConnectionID";Expression={$_.split(".")[1].split(" ")[0]}}, @{Name="IPAddress";Expression={$_.split()[9]}} | sort-object -unique IPAddress ) -join("|")
</code>```

Title: Powershell - comparing lines

Body:
I need to parse through a file and when lines with the same connection-ID (655629, in this example) are found, compare them and only keep the one that is not 'other'

These two lines, for example:

08/26-20:26:42.655629  [**] [1:9000003:0] troll [**] [Priority: 0] {TCP} 192.168.0.1:35964 -> 192.168.0.99:368
08/26-20:26:42.655629  [**] [1:1:0] other [**] [Priority: 0] {TCP} 192.168.0.1:35964 -> 192.168.0.99:368

Someone here was already kind enough to share this code, that basically returns the parts of each line that I need, formatted the way that I need.

Get-Content $logFile -ReadCount 1 | % {
'|' + (($_.Split()[0, 9, 11, 4] -replace ':', '|') -join '|') + '|'
} | Out-File "C:\Log\logout.txt"

|08/26-20|26|42.655629|192.168.0.1|35964|192.168.0.99|368|troll|
|08/26-20|26|42.655629|192.168.0.1|35964|192.168.0.99|368|other|

However, I only want to keep one line when there are multiple lines with the same connection ID (655629 in this example). In cases when there are multiple lines with the same connection ID, I need the line that is NOT 'other'

I'm showing that first indice [0] only for comparison-sake. I need to remove it from the final output for all lines.

For example, final output should look something like this:

|192.168.0.1|35964|192.168.0.99|368|troll|
|192.168.0.254|35964|192.168.0.99|368|troll|
|192.168.0.9|35964|192.168.0.99|368|other|
|192.168.0.199|35964|192.168.0.99|368|troll|
|192.168.0.199|35964|192.168.0.99|368|other|

Any help is much appreciated!

Body:
If the last field that you want to remove is always going to be 'other', you could add a where-object filter to remove them.

Get-Content $logFile -ReadCount 1 | % {
'|' + (($_.Split()[0, 9, 11, 4] -replace ':', '|') -join '|') + '|'
} | where-object {$_ -notlike "*other|"} | Out-File "C:\Log\logout.txt"

If 'other' is representative of something else, you could use a -UNIQUE option and see about filtering to only a single copy of each. Problem being you don't currently name the fields, which you could do via expressions..

(Get-Content $logFile -ReadCount 1 | select @{name="DateTime";Expression={$_.split(" ")[0].split(".")[0]}}, @{name="ConnectionID";Expression={$_.split(".")[1].split(" ")[0]}}, @{Name="IPAddress";Expression={$_.split()[9]}} | sort-object -unique IPAddress ) -join("|")


问:
How to use a csv file with the google chart API?
I have a csv file with that :

Site,Janvier,Février,Mars,Avril,Mai,Juin,Juillet,Août,Septembre,Octobre,Novembre,Décembre
CITROEN VILLEFRANCHE CARROSSERIE,0,0,14,0,18,21,0,0,0,0,0,0
CITROEN VILLEFRANCHE            ,240,237,230,264,219,285,219,130,4,0,0,0
NISSAN VILLEFRANCHE             ,174,202,215,181,196,244,203,107,10,1,0,0

I would like to see its data in a column chart.

But i do not know how to read the data of a csv with the API.
Here is an example of a column chart with the API :

```<code>google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ["Element", "Density", { role: "style" } ],
    ["Copper", 8.94, "#b87333"],
    ["Silver", 10.49, "silver"],
    ["Gold", 19.30, "gold"],
    ["Platinum", 21.45, "color: #e5e4e2"]
  ]);

  var view = new google.visualization.DataView(data);
  view.setColumns([0, 1,
                   { calc: "stringify",
                     sourceColumn: 1,
                     type: "string",
                     role: "annotation" },
                   2]);

  var options = {
    title: "Density of Precious Metals, in g/cm^3",
    width: 600,
    height: 400,
    bar: {groupWidth: "95%"},
    legend: { position: "none" },
  };
  var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
  chart.draw(view, options);
</code>```

How to change the data load to use a csv file ?

答:
you can use jquery.csv to parse the csv

```<code>google.charts.load('current', {
  callback: function () {
    $.get("file_name.csv", function(csvString) {
      var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});

      var data = new google.visualization.arrayToDataTable(arrayData);

      var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
      chart.draw(data);
    });
  },
  packages: ['corechart']
});
</code>```

see following working snippet with static data

google.charts.load('current', {
  callback: function () {
    csvString = 'Site,Janvier,Février,Mars,Avril,Mai,Juin,Juillet,Août,Septembre,Octobre,Novembre,Décembre\nCITROEN VILLEFRANCHE CARROSSERIE,0,0,14,0,18,21,0,0,0,0,0,0\nCITROEN VILLEFRANCHE ,240,237,230,264,219,285,219,130,4,0,0,0\nNISSAN VILLEFRANCHE ,174,202,215,181,196,244,203,107,10,1,0,0';

    var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});

    var data = new google.visualization.arrayToDataTable(arrayData);

    var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
    chart.draw(data);
  },
  packages: ['corechart']
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<div id="chart_div"></div></code>```

Body:
I have a csv file with that :

Site,Janvier,Février,Mars,Avril,Mai,Juin,Juillet,Août,Septembre,Octobre,Novembre,Décembre
CITROEN VILLEFRANCHE CARROSSERIE,0,0,14,0,18,21,0,0,0,0,0,0
CITROEN VILLEFRANCHE            ,240,237,230,264,219,285,219,130,4,0,0,0
NISSAN VILLEFRANCHE             ,174,202,215,181,196,244,203,107,10,1,0,0

I would like to see its data in a column chart.

But i do not know how to read the data of a csv with the API.
Here is an example of a column chart with the API :

google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ["Element", "Density", { role: "style" } ],
    ["Copper", 8.94, "#b87333"],
    ["Silver", 10.49, "silver"],
    ["Gold", 19.30, "gold"],
    ["Platinum", 21.45, "color: #e5e4e2"]
  ]);

  var view = new google.visualization.DataView(data);
  view.setColumns([0, 1,
                   { calc: "stringify",
                     sourceColumn: 1,
                     type: "string",
                     role: "annotation" },
                   2]);

  var options = {
    title: "Density of Precious Metals, in g/cm^3",
    width: 600,
    height: 400,
    bar: {groupWidth: "95%"},
    legend: { position: "none" },
  };
  var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
  chart.draw(view, options);

How to change the data load to use a csv file ?

Body:
you can use jquery.csv to parse the csv

google.charts.load('current', {
  callback: function () {
    $.get("file_name.csv", function(csvString) {
      var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});

      var data = new google.visualization.arrayToDataTable(arrayData);

      var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
      chart.draw(data);
    });
  },
  packages: ['corechart']
});

see following working snippet with static data

google.charts.load('current', {
  callback: function () {
    csvString = 'Site,Janvier,Février,Mars,Avril,Mai,Juin,Juillet,Août,Septembre,Octobre,Novembre,Décembre\nCITROEN VILLEFRANCHE CARROSSERIE,0,0,14,0,18,21,0,0,0,0,0,0\nCITROEN VILLEFRANCHE ,240,237,230,264,219,285,219,130,4,0,0,0\nNISSAN VILLEFRANCHE ,174,202,215,181,196,244,203,107,10,1,0,0';

    var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});

    var data = new google.visualization.arrayToDataTable(arrayData);

    var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
    chart.draw(data);
  },
  packages: ['corechart']
});

<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<div id="chart_div"></div>


问:
Error message ORA-19279: XPTY0004 received when trying to create view of XML file in PL/SQL
I am trying to create a view of some XML files in Oracle PL/SQL. The problem with the data content of the XML files is that a single path often has more than one data entry, as shown below:

```<code><priip>
  <data>
    <properties>
      <priipMonitoringInterval>daily</priipMonitoringInterval>
      <priipMonitoringStartDate>2017-06-30T13:51:03.168000</priipMonitoringStartDate>
      <permittedKIDDownloadJurisdictions>
        <item>DE</item>
        <item>AT</item>
      </permittedKIDDownloadJurisdictions>
    </properties>
  </data>
</priip>
</code>```

I am hence getting an error message which reads:

ORA-19279: XPTY0004 - XQuery dynamic type mismatch: expected singleton sequence - got multi-item sequence

Here, clearly, the problem lies with the path:

```<code>priip/data/properties/permittedKIDDownloadJurisdictions/item
</code>```

where we have two permissible jurisdictions, DE and AT. I cannot change the raw XML file, and I require all data within the files to be entered into the PL/SQL view. I have attached a sample of my code below, showing what I have already tried to do.

```<code>create or replace view PRIIPS_XML_VIEW as
  select *
    from PRIIPS_XML t,
      XMLTable(
        '$p/priip/data'
        passing t.SYS_NC_ROWINFO$ as "p"

        columns
          priip_monitoring_interval varchar2(20) path 'properties/priipMonitoringInterval',
          priip_monitoring_start_date varchar2(26) path 'properties/priipMonitoringStartDate',
          kid_download_jurisdiction varchar2(10) path 'properties/permittedKIDDownloadJurisdictions/item'
          );
</code>```

Any help would be greatly appreciated!

答:
Since Item occurs more than once it should be dealt with using a second XMLTABLE operations. This will give a normalized view of the item content.

See https://livesql.oracle.com/apex/livesql/file/content_E8GUH32UJN0EDKXRSV30ZUX4V.html

Body:
I am trying to create a view of some XML files in Oracle PL/SQL. The problem with the data content of the XML files is that a single path often has more than one data entry, as shown below:

<priip>
  <data>
    <properties>
      <priipMonitoringInterval>daily</priipMonitoringInterval>
      <priipMonitoringStartDate>2017-06-30T13:51:03.168000</priipMonitoringStartDate>
      <permittedKIDDownloadJurisdictions>
        <item>DE</item>
        <item>AT</item>
      </permittedKIDDownloadJurisdictions>
    </properties>
  </data>
</priip>

I am hence getting an error message which reads:

ORA-19279: XPTY0004 - XQuery dynamic type mismatch: expected singleton sequence - got multi-item sequence

Here, clearly, the problem lies with the path:

priip/data/properties/permittedKIDDownloadJurisdictions/item

where we have two permissible jurisdictions, DE and AT. I cannot change the raw XML file, and I require all data within the files to be entered into the PL/SQL view. I have attached a sample of my code below, showing what I have already tried to do.

create or replace view PRIIPS_XML_VIEW as
  select *
    from PRIIPS_XML t,
      XMLTable(
        '$p/priip/data'
        passing t.SYS_NC_ROWINFO$ as "p"

        columns
          priip_monitoring_interval varchar2(20) path 'properties/priipMonitoringInterval',
          priip_monitoring_start_date varchar2(26) path 'properties/priipMonitoringStartDate',
          kid_download_jurisdiction varchar2(10) path 'properties/permittedKIDDownloadJurisdictions/item'
          );

Any help would be greatly appreciated!


问:
Restarting Apache kill background process
I have a script startbg.php:

```<code>echo `/usr/bin/php $dir/runbg.php >> $dir/logbg.txt 2>&1 &`;
</code>```

Which I call from the web (via HTTP/Apache).

It runs runbg.php in a background process.

But if I restart Apache (/etc/init.d/apache2 restart), the background process is killed.

Is there anyway I can keep the process running in the background?

答: One way to allow the process to continue running without apache is to make it a service. Then activate the service (service runbg start) with your command. If you don't make the service normally running, then it will depend on your command to start after a reboot, but will not die with apache restarting.</p>

Body:
I have a script startbg.php:

echo `/usr/bin/php $dir/runbg.php >> $dir/logbg.txt 2>&1 &`;

Which I call from the web (via HTTP/Apache).

It runs runbg.php in a background process.

But if I restart Apache (/etc/init.d/apache2 restart), the background process is killed.

Is there anyway I can keep the process running in the background?


问:
IBM watson rank and retrieve training the ranker getting Value error: No JSON could be decoded
I am trying to use the IBM Watson Rank and Retrieve service and I am following the tutorial with the sample data present in the portal i.e cranfield-data. However when I am trying to train the ranker using train.py I am getting the following error:

note: 1) I have uploaded the required JSON files
2) I am running the code in python2 environment.

Any help?

答:
Which file from the tutorial are you passing in as the -i {relevance_file} parameter? Is it this one: https://watson-developer-cloud.github.io/doc-tutorial-downloads/retrieve-and-rank/cranfield-gt.csv?

Other things to check:

The collection was created properly when you uploaded the https://watson-developer-cloud.github.io/doc-tutorial-downloads/retrieve-and-rank/cranfield-data.json (a search with the query q=*:* should yield 1400 results)

The train.py file wasn't modified after download from https://watson-developer-cloud.github.io/doc-tutorial-downloads/retrieve-and-rank/train.py


问:
Could not format sql correctly in pymysql
What I want is execute the sql
select * from articles where author like "%steven%".

For the sake of safety, i used like this way :

cursor.execute('select * from articles where %s like %s', ('author', '%steven%')

Then the result is just empty, not get a syntax error, but just empty set.
But I am pretty sure there is some thing inside, I can get result use the first sql. Is there anything run with my code ?

答:
You can't set a column name like a parameter where you're doing where %s like %s.  To dynamically set the column name you need to do actual string manipulation like:

```<code>sql = 'select * from articles where '+ sql_identifier('author') +' like %s'
cursor.execute(sql, ('%steven%',))
</code>```

Where sql_identifier is your lib's function for making an identifier safe for SQL injection.  Something like:

```<code># don't actually use this!
def sql_identifier(s):
  return '"%s"' % s.replace('"','')
</code>```

But with actual testing and knowledge of the DB engine you're using.

Body:
You can't set a column name like a parameter where you're doing where %s like %s.  To dynamically set the column name you need to do actual string manipulation like:

sql = 'select * from articles where '+ sql_identifier('author') +' like %s'
cursor.execute(sql, ('%steven%',))

Where sql_identifier is your lib's function for making an identifier safe for SQL injection.  Something like:

# don't actually use this!
def sql_identifier(s):
  return '"%s"' % s.replace('"','')

But with actual testing and knowledge of the DB engine you're using.


问:
bash - How to find the index of the maximum value of a row in a matrix
Here's my input :

```<code>chr1 58962 -0.042053 -22.525086 -20.817409 -19.525688
chr1 58989 -0.014479 -14.459352 -12.824315 -11.744024
chr1 59155 -0.062963 -13.810858 -12.749009 -12.102778
chr1 59256 -0.014105 -7.371202  -9.117587  -11.525907
</code>```

I'm looking for a way, in bash, to get the index of the maximum value of the row for each row. I don't want to take into account the first two columns.

I could do it very simply in R :

```<code>data=fread(myfile)
maxindex=apply(data[,3:6],1,which.max)
</code>```

So that the output is an array containing the index. This is the kind of output I want in the end. In this case :

```<code>maxindex= 1  1  1  1
</code>```

Unfortunately the whole file is 32 Gb (big table containing 300000 rows and 8183 columns) so that R can't take it even after I subsidized the original file. I've read that bash isn't made to work by row but is there still a way to do what I want to do?

答:
If you want the script written with basic bash operations, you could do something like this:

```<code>#!/bin/bash

# Function to find the max-value of a one-dimensional array
findMax()
{
    [[ -z $2 ]] && return # Exit early if the string is empty

    declare -a pararr=($@) #Insert the input into an array we can work with

    # Basic brute-force algorithm to find the highest value in the array
    maxInd=2
    for (( i = 3; i < $#; i++ )); do
        (( $(echo "${pararr[$i]} > ${pararr[$maxInd]}" | bc) )) && maxInd=$i
    done

    echo -n " $(( maxInd - 2 ))"
}

echo -n "Maxindex:"

# Feed our findMax row-by-row from the input file
while read -r line; do
    findMax $line
done < ${!#}

echo # Append newline at the end
</code>```

This script takes a file that is formatted as your example, and searches for the max index row by row. However, in the file each row must be seperated by a newline like your example shows, else some wonky stuff may happen. You can of course extend the script to deal with other formats if you wish.

However if you want to do this operation on very large files, i think the solutions provided by the others here will be much better suited. I don't really know much about the overhead of bash since i use C/C++ for most performance-critical applications, but im guessing it's not very efficient.

```<code>(( $(echo "${pararr[$i]} > ${pararr[$maxInd]}" | bc) )) && maxInd=$i
</code>```

This part of the script is really ugly, but i dont know of any better way to do floating-point arithmetic. What we are doing here is we are evaluating our current position in the row with the largest value we have found so far. So this:

```<code>echo "${pararr[$i]} > ${pararr[$maxInd]}
</code>```

Might expand to something like this

```<code>0.356 > 1.567
</code>```

We then pipe it into bc which does the floating-point comparisons for us. If our current position is greater than the greatest value we have found so far, we set our maxIndex to that value. Hope this helps.

Body:
Here's my input :

chr1 58962 -0.042053 -22.525086 -20.817409 -19.525688
chr1 58989 -0.014479 -14.459352 -12.824315 -11.744024
chr1 59155 -0.062963 -13.810858 -12.749009 -12.102778
chr1 59256 -0.014105 -7.371202  -9.117587  -11.525907

I'm looking for a way, in bash, to get the index of the maximum value of the row for each row. I don't want to take into account the first two columns.

I could do it very simply in R :

data=fread(myfile)
maxindex=apply(data[,3:6],1,which.max)

So that the output is an array containing the index. This is the kind of output I want in the end. In this case :

maxindex= 1  1  1  1

Unfortunately the whole file is 32 Gb (big table containing 300000 rows and 8183 columns) so that R can't take it even after I subsidized the original file. I've read that bash isn't made to work by row but is there still a way to do what I want to do?

Body:
If you want the script written with basic bash operations, you could do something like this:

#!/bin/bash

# Function to find the max-value of a one-dimensional array
findMax()
{
    [[ -z $2 ]] && return # Exit early if the string is empty

    declare -a pararr=($@) #Insert the input into an array we can work with

    # Basic brute-force algorithm to find the highest value in the array
    maxInd=2
    for (( i = 3; i < $#; i++ )); do
        (( $(echo "${pararr[$i]} > ${pararr[$maxInd]}" | bc) )) && maxInd=$i
    done

    echo -n " $(( maxInd - 2 ))"
}

echo -n "Maxindex:"

# Feed our findMax row-by-row from the input file
while read -r line; do
    findMax $line
done < ${!#}

echo # Append newline at the end

This script takes a file that is formatted as your example, and searches for the max index row by row. However, in the file each row must be seperated by a newline like your example shows, else some wonky stuff may happen. You can of course extend the script to deal with other formats if you wish.

However if you want to do this operation on very large files, i think the solutions provided by the others here will be much better suited. I don't really know much about the overhead of bash since i use C/C++ for most performance-critical applications, but im guessing it's not very efficient.

(( $(echo "${pararr[$i]} > ${pararr[$maxInd]}" | bc) )) && maxInd=$i

This part of the script is really ugly, but i dont know of any better way to do floating-point arithmetic. What we are doing here is we are evaluating our current position in the row with the largest value we have found so far. So this:

echo "${pararr[$i]} > ${pararr[$maxInd]}

Might expand to something like this

0.356 > 1.567

We then pipe it into bc which does the floating-point comparisons for us. If our current position is greater than the greatest value we have found so far, we set our maxIndex to that value. Hope this helps.


问:
Define spring property values in Java
I have some spring beans which wire in property values using the @Value annotation.

e.g.

```<code>@Value("${my.property}")
private String myField;
</code>```

Usually the values are sourced from property files.

The test I am currently writing uses a fully annotation based configuration.

e.g.

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class AcceptanceTest implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Configuration
    @ComponentScan(basePackages = {
        "my.package.one",
        "my.package.two"
    })
    static class ContextConfiguration {
        @Bean
        public MyBean getMyBean(){
            return new MyBean();
        }
    }

    @Autowired
    private AnotherBean anotherBean;

    @Test
    public void testTest(){
        assertNotNull(anotherBean);
        . . .
    }
    . . .
</code>```

I don't wish to reference an external properties file, as I want to keep everything local to the test.

Is there anyway I can specify in java, values for such properties, so that they will be wired in automatically to any beans which need them.

Any help would be appreciated.

答:
If you are using Spock you can also use @TestPropertySource:

```<code>@SpringBootTest
@TestPropertySource(properties = [ "my.test.property = bar", "..." ])
</code>```

It requires the String array to be in Groovy syntax of course, caught me out. I'm using Spock 1.1

Title: Define spring property values in Java

Body:
I have some spring beans which wire in property values using the @Value annotation.

e.g.

@Value("${my.property}")
private String myField;

Usually the values are sourced from property files.

The test I am currently writing uses a fully annotation based configuration.

e.g.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class AcceptanceTest implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Configuration
    @ComponentScan(basePackages = {
        "my.package.one",
        "my.package.two"
    })
    static class ContextConfiguration {
        @Bean
        public MyBean getMyBean(){
            return new MyBean();
        }
    }

    @Autowired
    private AnotherBean anotherBean;

    @Test
    public void testTest(){
        assertNotNull(anotherBean);
        . . .
    }
    . . .

I don't wish to reference an external properties file, as I want to keep everything local to the test.

Is there anyway I can specify in java, values for such properties, so that they will be wired in automatically to any beans which need them.

Any help would be appreciated.

Body:
If you are using Spock you can also use @TestPropertySource:

@SpringBootTest
@TestPropertySource(properties = [ "my.test.property = bar", "..." ])

It requires the String array to be in Groovy syntax of course, caught me out. I'm using Spock 1.1


问:
Can't use preg_replace inside a static function, why?
Is there any reason why I can't use preg_replace inside a static function? when I move the code out of it, it works perfectly. Any ideas?</p>

答:
preg_replace is a core php function and can be used at any scope.

perhaps you are using it to evaluate a class member in the static method?  that would not work.  but I couldn't say for sure without seeing a relevant chunk of code.


问:
Make a Firebase Child ref with react Native
How can I make a reference to a key using a relative path ? I want to target the "likes" child of item1/items2, etc...those are key I created myself.
Here is my json file:

```<code>{
    "items": {
        "items1": {
            "french": "fdjsfd",
            "english": "feeds",
            "english_erudite": "fdsfds",
            "likes":"0",
            },
          "items2": {
            "french": "fdfsd",
            "english": "fdsfsd",
            "english_erudite": "feeds",
            "likes":"0",
            }
          }
}
</code>```

Right now I have this, but it adds a new child to the node "items" instead of going to items>items1>likes:

```<code>var ref = firebase.database().ref();

var likes_words = ref.child("items").child("???").child("likes");

likes_words.transaction(function(currentLike) {
   return currentLike + 1;
});
}
</code>```

答:
Just adjust your code to this</p>

```<code> var ref = firebase.database().ref();

            var likes_words = ref.child("items").once('value');

                likes_words.then(items => {
                    items.forEach(item => {

                       //for each item do this
                       let currentlike = item.val().likes;
                     ref.child("items/"+item.key+"/likes").update((currentlike+1));

                    })
               });
</code>```

Body:
How can I make a reference to a key using a relative path ? I want to target the "likes" child of item1/items2, etc...those are key I created myself.
Here is my json file:

{
    "items": {
        "items1": {
            "french": "fdjsfd",
            "english": "feeds",
            "english_erudite": "fdsfds",
            "likes":"0",
            },
          "items2": {
            "french": "fdfsd",
            "english": "fdsfsd",
            "english_erudite": "feeds",
            "likes":"0",
            }
          }
}

Right now I have this, but it adds a new child to the node "items" instead of going to items>items1>likes:

var ref = firebase.database().ref();

var likes_words = ref.child("items").child("???").child("likes");

likes_words.transaction(function(currentLike) {
   return currentLike + 1;
});
}

Body:
Just adjust your code to this

 var ref = firebase.database().ref();

            var likes_words = ref.child("items").once('value');

                likes_words.then(items => {
                    items.forEach(item => {

                       //for each item do this
                       let currentlike = item.val().likes;
                     ref.child("items/"+item.key+"/likes").update((currentlike+1));

                    })
               });


问:
How to select a MultipleChoice option based on text variable
I have a MultipleChoiceField and a variable my_choice = 'mystring'

I want check the option relative to my_choice

Here my html:

```<code>    ul id="id_layer_select"><li><label for="id_layer_select_0"><input checked="checked" id="id_layer_select_0" name="layer_select" type="checkbox" value="1" /> <span style='font-weight:normal'>Mychoice1</span></label></li>
<li><label for="id_layer_select_1"><input id="id_layer_select_1" name="layer_select" type="checkbox" value="2" /> <span style='font-weight:normal'>Mychoice2</span></label></li>
<li><label for="id_layer_select_2"><input id="id_layer_select_2" name="layer_select" type="checkbox" value="3" /> <span style='font-weight:normal'>Mychoice3</span></label></li> [...]</ul>
</code>```

here my javascript:

```<code>var my_choice = 'mystring'
var opt = $("#id_layer_select option");
opt.filter("[value=my_choice]").attr("selected", true);
</code>```

I can use jquery. Thank you

PS: Off course mystring is an option Mychoice1 or Mychoice2 or etc.

I don't want use the id_layer_select_x and I prefer to not add and attribute.

The problem is that the checkbox stay unchecked and

```<code>console.log(opt)=Object { length: 0, prevObject: Object[1] }
</code>```

答:
You can filter all spans by the text they contain. You can then get the previous element and have it checked.

$(document).ready(function() {
  var txt = "Mychoice3";

  var labelMatchingTxt = $('#id_layer_select span').filter(function(i, el) {
    return txt === el.childNodes[0].nodeValue; // avoiding DOM reselection.
  }).prev().prop('checked', true);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></head>

<body>

<ul id="id_layer_select"><li><label for="id_layer_select_0"><input id="id_layer_select_0" name="layer_select" type="checkbox" value="1" /> <span style='font-weight:normal'>Mychoice1</span></label></li>
<li><label for="id_layer_select_1"><input id="id_layer_select_1" name="layer_select" type="checkbox" value="2" /> <span style='font-weight:normal'>Mychoice2</span></label></li>
<li><label for="id_layer_select_2"><input id="id_layer_select_2" name="layer_select" type="checkbox" value="3" /> <span style='font-weight:normal'>Mychoice3</span></label></li> [...]</ul>
</body></code>```

Body:
I have a MultipleChoiceField and a variable my_choice = 'mystring'

I want check the option relative to my_choice

Here my html:

    ul id="id_layer_select">
<input checked="checked" id="id_layer_select_0" name="layer_select" type="checkbox" value="1" /> Mychoice1

<input id="id_layer_select_1" name="layer_select" type="checkbox" value="2" /> Mychoice2

<input id="id_layer_select_2" name="layer_select" type="checkbox" value="3" /> Mychoice3
 [...]

here my javascript:

var my_choice = 'mystring'
var opt = $("#id_layer_select option");
opt.filter("[value=my_choice]").attr("selected", true);

I can use jquery. Thank you

PS: Off course mystring is an option Mychoice1 or Mychoice2 or etc.

I don't want use the id_layer_select_x and I prefer to not add and attribute.

The problem is that the checkbox stay unchecked and

console.log(opt)=Object { length: 0, prevObject: Object[1] }

Body:
You can filter all spans by the text they contain. You can then get the previous element and have it checked.

$(document).ready(function() {
  var txt = "Mychoice3";

  var labelMatchingTxt = $('#id_layer_select span').filter(function(i, el) {
    return txt === el.childNodes[0].nodeValue; // avoiding DOM reselection.
  }).prev().prop('checked', true);
});

<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></head>

<body>

<ul id="id_layer_select"><li><label for="id_layer_select_0"><input id="id_layer_select_0" name="layer_select" type="checkbox" value="1" /> <span style='font-weight:normal'>Mychoice1</span></label></li>
<li><label for="id_layer_select_1"><input id="id_layer_select_1" name="layer_select" type="checkbox" value="2" /> <span style='font-weight:normal'>Mychoice2</span></label></li>
<li><label for="id_layer_select_2"><input id="id_layer_select_2" name="layer_select" type="checkbox" value="3" /> <span style='font-weight:normal'>Mychoice3</span></label></li> [...]</ul>
</body>


问:
Abort trap 6 in array joining function
I'm trying to join the arrays together using a function. It works somehow but prompts an error abort trap 6. In addition, it also says that I cannot free the allocated memory.</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int *join_arrays(unsigned int arr1N, int arr1[], unsigned int arr2N, int arr2[], unsigned int arr3N, int arr3[]) {
  int tableLen = arr1N + arr2N + arr3N;
  printf("%d\n", tableLen);
  int *table = malloc(tableLen * sizeof(int));
  table = arr1;
  printf("%d\n", table[arr1N - 1]);
  for (int i = 0; i < arr2N; i++) {
   table[i + arr1N] = arr2[i];
  }
  printf("%d\n", table[arr1N + arr2N - 1]);
  for (int j = 0; j < arr3N; j++) {
   table[j + arr1N + arr2N] = arr3[j];
  }

  return table;
}

int main(void)
{
    int a1[] = { 89, 53, 98, 5, 5, 49, 95, 9, 54, 59, 59 };
    int a2[] = { 44, 25, 0, 0, 0, 0, 0, 0, 0, 0, 80, 0, 144, 0, 0, 0, 0};
    int a3[] = { 20, 21, 22 };

    int *joined = join_arrays(11, a1, 17, a2, 3, a3);

    for (int i = 0; i < 11 + 17 + 3; i++) {
        printf("%d  ", joined[i]);
    }
    printf("\n");

    free(joined);

    return 0;
}
</code>```

答:
The function is wrong. At least there is a memory leak. At first the pointer table points to the allocated memory but then it is reassigned and points to the first character of the first array passed to the function as argument.

```<code>int *table = malloc(tableLen * sizeof(int));
table = arr1;
</code>```

So the two loops used in the function try to copy to the first array and as result they access memory beyond the array.

Take into account that it is much better to change the order of the function parameters. At first there should be specified an array and only then its size. Also the arrays should be declared with qualifier const and their sizes as having type size_t.

Also it is a bad idea to use magic numbers like 11, 17, and 3. Usually such a usage is a reason for program bugs.

You could use standard C function memcpy instead of the loops.

The program can look the following way

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int * join_arrays( const int a1[], size_t n1,
                   const int a2[], size_t n2,
                   const int a3[], size_t n3 )
{
    int *joined = malloc( ( n1 + n2 + n3 ) * sizeof( int ) );

    if ( joined != NULL )
    {
        memcpy( joined, a1, n1 * sizeof( int ) );
        memcpy( joined + n1, a2, n2 * sizeof( int ) );
        memcpy( joined + n1 + n2, a3, n3 * sizeof( int ) );
    }

    return joined;
}

int main( void )
{
    int a1[] = { 89, 53, 98, 5, 5, 49, 95, 9, 54, 59, 59 };
    int a2[] = { 44, 25, 0, 0, 0, 0, 0, 0, 0, 0, 80, 0, 144, 0, 0, 0, 0};
    int a3[] = { 20, 21, 22 };

    size_t n1 = sizeof( a1 ) / sizeof( *a1 );
    size_t n2 = sizeof( a2 ) / sizeof( *a2 );
    size_t n3 = sizeof( a3 ) / sizeof( *a3 );

    int *joined = join_arrays( a1, n1, a2, n2, a3, n3 );

    if ( joined != NULL )
    {
        for ( size_t i = 0, n = n1 + n2 + n3; i < n; i++ )
        {
            printf( "%d  ", joined[i] );
        }
        printf( "\n" );
    }

    free( joined );

    return 0;
}
</code>```

Its output is

```<code>89  53  98  5  5  49  95  9  54  59  59  44  25  0  0  0  0  0  0  0  0  80  0  144  0  0  0  0  20  21  22
</code>```

Title: Abort trap 6 in array joining function

Body:
I'm trying to join the arrays together using a function. It works somehow but prompts an error abort trap 6. In addition, it also says that I cannot free the allocated memory.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int *join_arrays(unsigned int arr1N, int arr1[], unsigned int arr2N, int arr2[], unsigned int arr3N, int arr3[]) {
  int tableLen = arr1N + arr2N + arr3N;
  printf("%d\n", tableLen);
  int *table = malloc(tableLen * sizeof(int));
  table = arr1;
  printf("%d\n", table[arr1N - 1]);
  for (int i = 0; i < arr2N; i++) {
   table[i + arr1N] = arr2[i];
  }
  printf("%d\n", table[arr1N + arr2N - 1]);
  for (int j = 0; j < arr3N; j++) {
   table[j + arr1N + arr2N] = arr3[j];
  }

  return table;
}

int main(void)
{
    int a1[] = { 89, 53, 98, 5, 5, 49, 95, 9, 54, 59, 59 };
    int a2[] = { 44, 25, 0, 0, 0, 0, 0, 0, 0, 0, 80, 0, 144, 0, 0, 0, 0};
    int a3[] = { 20, 21, 22 };

    int *joined = join_arrays(11, a1, 17, a2, 3, a3);

    for (int i = 0; i < 11 + 17 + 3; i++) {
        printf("%d  ", joined[i]);
    }
    printf("\n");

    free(joined);

    return 0;
}

Body:
The function is wrong. At least there is a memory leak. At first the pointer table points to the allocated memory but then it is reassigned and points to the first character of the first array passed to the function as argument.

int *table = malloc(tableLen * sizeof(int));
table = arr1;

So the two loops used in the function try to copy to the first array and as result they access memory beyond the array.

Take into account that it is much better to change the order of the function parameters. At first there should be specified an array and only then its size. Also the arrays should be declared with qualifier const and their sizes as having type size_t.

Also it is a bad idea to use magic numbers like 11, 17, and 3. Usually such a usage is a reason for program bugs.

You could use standard C function memcpy instead of the loops.

The program can look the following way

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int * join_arrays( const int a1[], size_t n1,
                   const int a2[], size_t n2,
                   const int a3[], size_t n3 )
{
    int *joined = malloc( ( n1 + n2 + n3 ) * sizeof( int ) );

    if ( joined != NULL )
    {
        memcpy( joined, a1, n1 * sizeof( int ) );
        memcpy( joined + n1, a2, n2 * sizeof( int ) );
        memcpy( joined + n1 + n2, a3, n3 * sizeof( int ) );
    }

    return joined;
}

int main( void )
{
    int a1[] = { 89, 53, 98, 5, 5, 49, 95, 9, 54, 59, 59 };
    int a2[] = { 44, 25, 0, 0, 0, 0, 0, 0, 0, 0, 80, 0, 144, 0, 0, 0, 0};
    int a3[] = { 20, 21, 22 };

    size_t n1 = sizeof( a1 ) / sizeof( *a1 );
    size_t n2 = sizeof( a2 ) / sizeof( *a2 );
    size_t n3 = sizeof( a3 ) / sizeof( *a3 );

    int *joined = join_arrays( a1, n1, a2, n2, a3, n3 );

    if ( joined != NULL )
    {
        for ( size_t i = 0, n = n1 + n2 + n3; i < n; i++ )
        {
            printf( "%d  ", joined[i] );
        }
        printf( "\n" );
    }

    free( joined );

    return 0;
}

Its output is

89  53  98  5  5  49  95  9  54  59  59  44  25  0  0  0  0  0  0  0  0  80  0  144  0  0  0  0  20  21  22


问:
Memory Leak (char[])
When I run my program, it can run for a while, then all of the sudden, it experiences a huge memory leak. I traced it out using a snapshot of the heap when it crashed, and I have a mysterious char[] with the size of 232,023,801 Bytes. The minutes preceding crash have no unusual behavior until then. The only places where I use char arrays is in the following piece of code:

```<code>string ReadString(DWORD64 addr) {

    char* buffer = new char[128];

    bool validChar = true;
    for (int c = 0; c < 128 && validChar; c++) {
        buffer[c] = Mem.Read<char>(addr+ (0x1 * c), sizeof(char));
        if (!isalnum(buffer[c]) && !ispunct(buffer[c]))
            validChar = false;
    }
    string ret= string(buffer);
    delete[] buffer;
    return ret;
}
</code>```

All this code should be doing is reading a few characters from memory, saving the char array to a string, cleaning up the array, and returning the string. How is the memory leak originating from here? Or does the char[] in the heap snapshot potentially point to another issue?

答:
Assuming that string here is std::string:

You call string(buffer) which assumes that buffer is 0-terminated and allocates a new string. But your code doesn't ensure that buffer is actually 0-terminated, so this can cause undefined behavior, including potentially crashing or allocating too much memory for the string.

You probably want to use the string(buffer, size) constructor instead, which doesn't require buffer to be 0-terminated.

I'd also recommend avoiding the manual new/delete. One way to do this is to create an empty string and push_back the characters you read to it. This avoid the need for buffer.

Title: Memory Leak (char[])

Body:
When I run my program, it can run for a while, then all of the sudden, it experiences a huge memory leak. I traced it out using a snapshot of the heap when it crashed, and I have a mysterious char[] with the size of 232,023,801 Bytes. The minutes preceding crash have no unusual behavior until then. The only places where I use char arrays is in the following piece of code:

string ReadString(DWORD64 addr) {

    char* buffer = new char[128];

    bool validChar = true;
    for (int c = 0; c < 128 && validChar; c++) {
        buffer[c] = Mem.Read<char>(addr+ (0x1 * c), sizeof(char));
        if (!isalnum(buffer[c]) && !ispunct(buffer[c]))
            validChar = false;
    }
    string ret= string(buffer);
    delete[] buffer;
    return ret;
}

All this code should be doing is reading a few characters from memory, saving the char array to a string, cleaning up the array, and returning the string. How is the memory leak originating from here? Or does the char[] in the heap snapshot potentially point to another issue?


问:
Add 1 in an sql field when a div is clicked
I have a page where photos are uploaded, when you see the photos there is a button to give you points to the photo.

To the button I gave an onclick with a javascript function that has this php code

```<code>function puntos(){
        <?php
        mysql_query("UPDATE 'fotos' SET 'relevancia=relevancia+1' WHERE 'id = $id'");
        ?>
    }
</code>```

This is in photo.view.php in photo.php I have this code that retrieves the id of the selected photo

```<code>$id = isset($_GET['id']) ? (int)$_GET['id'] : false;
</code>```

what am I doing wrong?

答:
You're far from home.

Back to basics first:

Server vs. client

mysql and PHP run on the server

JavaScript runs on the client in their browser.

This means javascript cannot access your database directly, you need to do a lot of work before you get there.

Detecting and reacting on a click is something JavaScript can do (and is quite adept at doing).

Communication

Normally when a page downloads it and the components it refers are sent from the server to the client over HTTP.

Once in the browser, to get something back from the client to the server the only way is to send another query or open up some network connection somehow from the client to the server which then transfers that content, or indicates somehow what happened on the client.

Traditionally this meant a form and a click resulting in a GET or POST HTTP request and a reload of the page in the browser.

That's till we got:

AJAX

Essentially the connection from the client to the server can also be initiated by JavaScript itself and it can talk to a server component (just like the browser can) without having to reload a page or having to submit a form or so). This allows one to create things where a click or even a move of the mouse (or anything else JavaScript can detect -it can detect a lot-) can result into data being sent to the server and answers collected by that JavaScript. If it updates the page (aka DOM) is up to the script to chose.

Server Side

Now having JavaScript on the client communicating with the server still isn't going to let said JavaScript update a database. So you need a sever side component that does stringent validations (the code you have above is a horror story from the security side should that ever get to work) and updates a database behind it as needed.

TL;DR

Suggest you read up more on how to do simple AJAX

Some starting points:

https://www.w3schools.com/xml/ajax_intro.asp

https://www.owasp.org/index.php/AJAX_Security_Cheat_Sheet

But there's much more out there for sure.

Body:
I have a page where photos are uploaded, when you see the photos there is a button to give you points to the photo.

To the button I gave an onclick with a javascript function that has this php code

function puntos(){
        <?php
        mysql_query("UPDATE 'fotos' SET 'relevancia=relevancia+1' WHERE 'id = $id'");
        ?>
    }

This is in photo.view.php in photo.php I have this code that retrieves the id of the selected photo

$id = isset($_GET['id']) ? (int)$_GET['id'] : false;

what am I doing wrong?


问:
How do I write a unit test that verifies a subroutine is called?
```<code>Public Class Class1

Public OutPut As String = ""
Public StoreThis As String = ""

Public Function GiveOutPut(ByVal s As String) As String

    OutPut = s + " OutPut"

    If s = "S" Then
        CallThis()
    End If

    Return OutPut

End Function

Public Sub CallThis()

    ///pretend something useful is going on here

End Sub

End Class
</code>```

Granted this example is pretty weak, but how could I write a test method that to prove that CallThis() gets called everytime that the input parameter s = "S"?

答:
If something useful happens in CallThis, you can detect the side effect in your test code.

For example, if a variable changes value in a specific way by this function, you can test its value before and after the call.

Body:
Public Class Class1

Public OutPut As String = ""
Public StoreThis As String = ""

Public Function GiveOutPut(ByVal s As String) As String

    OutPut = s + " OutPut"

    If s = "S" Then
        CallThis()
    End If

    Return OutPut

End Function

Public Sub CallThis()

    ///pretend something useful is going on here

End Sub

End Class

Granted this example is pretty weak, but how could I write a test method that to prove that CallThis() gets called everytime that the input parameter s = "S"?


问:
C# Update or insert from a List by some criteria
I have 2 lists, both with a different number of items, both with 1 parameter in common that I have to compare. If the value of the parameter is the same I have to update the DB, but if the item in a list doesn't have an item in the second list, I have to insert it into the DB.

This is what I was trying:

foreach (var rep in prodrep)
{
    foreach (var crm in prodcrm)
    {
        if (rep.VEHI_SERIE.Equals(crm.VEHI_SERIE))
        {
            updateRecord(rep.Data);

        }
        else
        {
            insertRecords(rep.Data);
        }
    }
}
```

The first problem with this is that it is very slow. The second problem is that obviously the insert statement would't work, but I don't want to do another for each inside a foreach to verify if it doesn't exist, because that would take double the time.

How can I make this more efficient?

答:
see Algorithm to optimize nested loops

it's an interesting read, and a cool trick, however not necessarily something that you should apply in every situation.

Also, be careful about answers providing you with LINQ queries. often it "looks cool" because you're not using the word "for", but really it's just hiding those for loops under the hood.

If you're really concerned about performance and the computer can handle it, you can look at the Task Parallel Library. it's not necessarily going to solve all of your problems, because you can be limited by processor/memory and you could end up making your application slower.

Is this something that a user of your application is going to be regularly doing? If so, is it something you can you make it an asynchronous task that they can come back to later, or is it an offline process that they aren't ever going to see. Depending on usage expectations, sometimes the time something takes isn't the end of the world.

Body:
I have 2 lists, both with a different number of items, both with 1 parameter in common that I have to compare. If the value of the parameter is the same I have to update the DB, but if the item in a list doesn't have an item in the second list, I have to insert it into the DB.

This is what I was trying:

foreach (var rep in prodrep)
{
    foreach (var crm in prodcrm)
    {
        if (rep.VEHI_SERIE.Equals(crm.VEHI_SERIE))
        {
            updateRecord(rep.Data);

        }
        else
        {
            insertRecords(rep.Data);
        }
    }
}

The first problem with this is that it is very slow. The second problem is that obviously the insert statement would't work, but I don't want to do another for each inside a foreach to verify if it doesn't exist, because that would take double the time.

How can I make this more efficient?


问:
Passing a long value from one fragment through the main activity to another fragment
I have a main_activity containing two fragments. When a button is clicked on beatTimeFragment, I want beatTimeFragment to determine the msec past 1970 that the button was pressed and pass it to toneTimeFragment by way of the main activity. The toneTimeFragment will then compare the response to a standard beat and give an offSet.

Every example i have seen passes string data rather than long data. In my code, I tried passing String data then converting it to long data. The string data gets transfered (i can was it show string). But the long gives a response of 0 or it kick me out if i do not have the exception.

Is there a way to get the conversion to work or if not, how do i set up for a long data transfer rather than String by removing the

```<code>beatTimeDisplay.getText().toString()
</code>```

at the end of the beatTimeFragment?

main_activity

```<code>public class MainActivity extends AppCompatActivity implements
BeatTimeFragment.BeatTimeListener{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

//Get called by BeatTimeFragment when button is pushed
@Override
public void sendBeatData(String beatTime) {
    ToneTimeFragment toneFragment = (ToneTimeFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
    toneFragment.setBeatLong(beatTime);
}
}
</code>```

toneTimeFragment

```<code>public class ToneTimeFragment extends Fragment {

public void setBeatLong(String beatTime) {
    try {
        beatTimeL = Long.parseLong(beatTime);
    } catch (NumberFormatException e) {
        System.out.println("NumberFormatException: " + e.getMessage());
    }
    // beatTimeL = Long.parseLong(beatTime);
    offSet = beatTimeL - toneTime;
    offSetView.setText(beatTime + " msec");
</code>```

beatTimeFragment

```<code>public class BeatTimeFragment extends Fragment {

private static Button beatBtn;
private static TextView beatTimeDisplay;
int q = 0;
long beatTime = 0;

//set up sending beatTime
BeatTimeListener activityCommander;

public interface BeatTimeListener{
    public void sendBeatData(String beatTime);
}

//setup to send data to top
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        activityCommander = (BeatTimeListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString());
    }
}

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.beat_time_fragment, container, false);

    beatTimeDisplay = (TextView) view.findViewById(R.id.beatTimeDisplay);
    final Button beatBtn = (Button) view.findViewById(R.id.beatBtn);

    beatBtn.setOnClickListener(
            new View.OnClickListener() {
                public void onClick(View v){

                    long beatTime= System.currentTimeMillis();
                    TextView view1 = (TextView) view.findViewById(R.id.beatTimeDisplay);
                    view1.setText(beatTime + " msec");
                    readySendBeat(v);

                }
            }

    );

    return view;
}

//calls to send data when button clicked
public void readySendBeat(View v) {
    activityCommander.sendBeatData(beatTimeDisplay.getText().toString());
     }
}
</code>```

答:
Try this, you dont need call to findViewById inside button listener, neither create duplicate long field:

MainActivity:

```<code>public class MainActivity extends AppCompatActivity implements
BeatTimeFragment.BeatTimeListener{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

//Get called by BeatTimeFragment when button is pushed
@Override
public void sendBeatData(long beatTime) {
    ToneTimeFragment toneFragment = (ToneTimeFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
    toneFragment.setBeatLong(beatTime);
}
}
</code>```

ToneTimeFragment:

```<code>public class ToneTimeFragment extends Fragment {

    public void setBeatLong(long beatTime) {
        try {
            beatTimeL = beatTime;
        } catch (NumberFormatException e) {
            System.out.println("NumberFormatException: " + e.getMessage());
        }
        offSet = beatTimeL - toneTime;
        offSetView.setText(beatTime + " msec");
</code>```

BeatTimeFragment:

```<code>public class BeatTimeFragment extends Fragment {

private static Button beatBtn;
private static TextView beatTimeDisplay;
int q = 0;
long beatTime = 0;

//set up sending beatTime
BeatTimeListener activityCommander;

public interface BeatTimeListener{
    public void sendBeatData(String beatTime);
}

//setup to send data to top
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        activityCommander = (BeatTimeListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString());
    }
}

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.beat_time_fragment, container, false);

    beatTimeDisplay = (TextView) view.findViewById(R.id.beatTimeDisplay);
    final Button beatBtn = (Button) view.findViewById(R.id.beatBtn);

    beatBtn.setOnClickListener(
            new View.OnClickListener() {
                public void onClick(View v){

                    beatTime= System.currentTimeMillis();
                    beatTimeDisplay.setText(beatTime + " msec");
                    readySendBeat(v);

                }
            }

    );

    return view;
}

//calls to send data when button clicked
public void readySendBeat() {
    activityCommander.sendBeatData(beatTime);
     }
}
</code>```

Body:
I have a main_activity containing two fragments. When a button is clicked on beatTimeFragment, I want beatTimeFragment to determine the msec past 1970 that the button was pressed and pass it to toneTimeFragment by way of the main activity. The toneTimeFragment will then compare the response to a standard beat and give an offSet.

Every example i have seen passes string data rather than long data. In my code, I tried passing String data then converting it to long data. The string data gets transfered (i can was it show string). But the long gives a response of 0 or it kick me out if i do not have the exception.

Is there a way to get the conversion to work or if not, how do i set up for a long data transfer rather than String by removing the

beatTimeDisplay.getText().toString()

at the end of the beatTimeFragment?

main_activity

public class MainActivity extends AppCompatActivity implements
BeatTimeFragment.BeatTimeListener{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

//Get called by BeatTimeFragment when button is pushed
@Override
public void sendBeatData(String beatTime) {
    ToneTimeFragment toneFragment = (ToneTimeFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
    toneFragment.setBeatLong(beatTime);
}
}

toneTimeFragment

public class ToneTimeFragment extends Fragment {

public void setBeatLong(String beatTime) {
    try {
        beatTimeL = Long.parseLong(beatTime);
    } catch (NumberFormatException e) {
        System.out.println("NumberFormatException: " + e.getMessage());
    }
    // beatTimeL = Long.parseLong(beatTime);
    offSet = beatTimeL - toneTime;
    offSetView.setText(beatTime + " msec");

beatTimeFragment

public class BeatTimeFragment extends Fragment {

private static Button beatBtn;
private static TextView beatTimeDisplay;
int q = 0;
long beatTime = 0;

//set up sending beatTime
BeatTimeListener activityCommander;

public interface BeatTimeListener{
    public void sendBeatData(String beatTime);
}

//setup to send data to top
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        activityCommander = (BeatTimeListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString());
    }
}

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.beat_time_fragment, container, false);

    beatTimeDisplay = (TextView) view.findViewById(R.id.beatTimeDisplay);
    final Button beatBtn = (Button) view.findViewById(R.id.beatBtn);

    beatBtn.setOnClickListener(
            new View.OnClickListener() {
                public void onClick(View v){

                    long beatTime= System.currentTimeMillis();
                    TextView view1 = (TextView) view.findViewById(R.id.beatTimeDisplay);
                    view1.setText(beatTime + " msec");
                    readySendBeat(v);

                }
            }

    );

    return view;
}

//calls to send data when button clicked
public void readySendBeat(View v) {
    activityCommander.sendBeatData(beatTimeDisplay.getText().toString());
     }
}

Body:
Try this, you dont need call to findViewById inside button listener, neither create duplicate long field:

MainActivity:

public class MainActivity extends AppCompatActivity implements
BeatTimeFragment.BeatTimeListener{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

//Get called by BeatTimeFragment when button is pushed
@Override
public void sendBeatData(long beatTime) {
    ToneTimeFragment toneFragment = (ToneTimeFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
    toneFragment.setBeatLong(beatTime);
}
}

ToneTimeFragment:

public class ToneTimeFragment extends Fragment {

    public void setBeatLong(long beatTime) {
        try {
            beatTimeL = beatTime;
        } catch (NumberFormatException e) {
            System.out.println("NumberFormatException: " + e.getMessage());
        }
        offSet = beatTimeL - toneTime;
        offSetView.setText(beatTime + " msec");

BeatTimeFragment:

public class BeatTimeFragment extends Fragment {

private static Button beatBtn;
private static TextView beatTimeDisplay;
int q = 0;
long beatTime = 0;

//set up sending beatTime
BeatTimeListener activityCommander;

public interface BeatTimeListener{
    public void sendBeatData(String beatTime);
}

//setup to send data to top
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        activityCommander = (BeatTimeListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString());
    }
}

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.beat_time_fragment, container, false);

    beatTimeDisplay = (TextView) view.findViewById(R.id.beatTimeDisplay);
    final Button beatBtn = (Button) view.findViewById(R.id.beatBtn);

    beatBtn.setOnClickListener(
            new View.OnClickListener() {
                public void onClick(View v){

                    beatTime= System.currentTimeMillis();
                    beatTimeDisplay.setText(beatTime + " msec");
                    readySendBeat(v);

                }
            }

    );

    return view;
}

//calls to send data when button clicked
public void readySendBeat() {
    activityCommander.sendBeatData(beatTime);
     }
}


问:
PHP/JQuery/AJAX form - server side validation only with in-line error styling
I'm working on a form that submits via AJAX and is processed using PHP. I am looking to have server side validation with inline styling to correspond to whichever field(s) are are not valid. I have a setup that mostly works, however, it only every validates one field at a time.

i.e. if the user tries to submit the form but leaves 2 fields blank, only the first of those 2 is highlighted with the .error-field class I created. I'd rather that any and all fields that have errors be highlighted at once. I know I can do such a thing in jQuery by using a loop, but I'm wondering if that's something that is possible here using only server-side validation? I don't want to print an error message for each field as the form is very small and I have very little space to work with. I'd prefer to just highlight the field(s) that produce an error then display the "Please fill in the required fields" message.

The HTML for the form:

```<code><form method="post" enctype="multipart/form-data" class="signupForm">
    <a class="sidebar">
        <span class="glyphicon glyphicon-arrow-left icon-arrow arrow"></span>
    </a>
    <a class="closeBtn">
        <span class="glyphicon glyphicon-remove"></span>
    </a>

    <h2 class="text-center black">Sign up for our newsletter.</h2>

    <p class="errors-container light">Please fill in the required fields.</p>

    <div class="success">Thank you for signing up!</div>
    <div class="form-field-content">
        <div class="form-group">
            <input class="form-control FirstNameTxt" type="text" name="first_name" placeholder="*First Name"
                   autofocus="">
        </div>
        <div class="form-group">
            <input class="form-control LastNameTxt" type="text" name="last_name" placeholder="*Last Name"
                   autofocus="">
        </div>
        <div class="form-group">
            <input class="form-control EmailTxt" type="email" name="email" placeholder="*Email"
                   autofocus="">
        </div>

        <div class="form-group submit-button">
            <button class="btn btn-primary btn-block button-submit" type="button">SIGN-UP</button>
            <img src="/img/ajax-loader.gif" class="progress" alt="Submitting...">
        </div>
    </div>
    <br/>
</form>
</code>```

The jQuery + AJAX:

```<code>;(function ($) {
    $(document).ready(function () {
        var FirstName = $('.FirstNameTxt');
        var LastName = $('.LastNameTxt');
        var EmailAddress = $('.EmailTxt');
        var successMessage = $('.success');
        var error = $('.errors-container');
        var submitbtn = $('.button-submit');
        var SubmitProgress = $('img.progress');

        var formdata = {};
        submitbtn.click(function (e) {
            resetErrors();
            postForm();
        });

        function resetErrors() {
            $('.signupForm input').removeClass('error-field');
        }

        function postForm() {
            $.each($('.signupForm input'), function(i, v) {
                if (v.type !== 'submit') {
                    formdata[v.name] = v.value;
                }
            });

            submitbtn.hide();
            error.hide();
            SubmitProgress.show();

            $.ajax({
                type: "POST",
                data: formdata,
                url: 'submission.php',
                dataType: "json"
            }).done(function (response) {
                submitbtn.show();
                SubmitProgress.hide();
                console.log("here");
                for (var i = 0; i < response.length; i++) {
                   var status = response[i].status;
                   var field = response[i].field;
                   if (status == "error") {
                     error.show();
                     $('input[name="' + field + '"]').addClass('error-field');
                   }
                    else if (status == "success") {
                        $('signupForm')[0].reset();
                        $('.form-field-content').hide();
                        successMessage.show();
                        $('.button-submit').html("Submitted");
                    }
                }
            });
        }
    });
}(jQuery));
</code>```

The php code that handles the form:

```<code>$firstname = $_POST['first_name'];
$lastname = $_POST['last_name'];
$emailfield = $_POST['email'];

$return = [];

if($firstname == ""){
    $validatonStatus = "error";
    $errorField = "first_name";
}
else if($lastname == ""){
    $validatonStatus = "error";
    $errorField = "last_name";
}
else if($emailfield == "" || !filter_var($emailfield, FILTER_VALIDATE_EMAIL)){
    $validatonStatus = "error";
    $errorField = "email";
}
else {
    $validatonStatus = "success";
    $errorField = "";
   //send email notification

}
$return[] = array(
    "status" => $validatonStatus,
    "field" => $errorField,
);

echo (json_encode($return));
</code>```

答:
The PHP code just returns an array with one element, not an element for each field. It needs to add a separate element to $return for each field.

It also shouldn't be using elseif, that prevents it from validating other fields when one is invalid.

```<code>if ($firstname == "") {
    $return[] = array('status' => 'error', 'field' => 'first_name');
} else {
    $return[] = array('status' => 'success', 'field' => 'first_name');
}

if ($lastname == "") {
    $return[] = array('status' => 'error', 'field' => 'last_name');
} else {
    $return[] = array('status' => 'success', 'field' => 'last_name');
}

if($emailfield == "" || !filter_var($emailfield, FILTER_VALIDATE_EMAIL)){
    $return[] = array('status' => 'error', 'field' => 'email');
} else {
    $return[] = array('status' => 'success', 'field' => 'email');
}
</code>```

Body:
I'm working on a form that submits via AJAX and is processed using PHP. I am looking to have server side validation with inline styling to correspond to whichever field(s) are are not valid. I have a setup that mostly works, however, it only every validates one field at a time.

i.e. if the user tries to submit the form but leaves 2 fields blank, only the first of those 2 is highlighted with the .error-field class I created. I'd rather that any and all fields that have errors be highlighted at once. I know I can do such a thing in jQuery by using a loop, but I'm wondering if that's something that is possible here using only server-side validation? I don't want to print an error message for each field as the form is very small and I have very little space to work with. I'd prefer to just highlight the field(s) that produce an error then display the "Please fill in the required fields" message.

The HTML for the form:

<form method="post" enctype="multipart/form-data" class="signupForm">

Sign up for our newsletter.

Please fill in the required fields.

Thank you for signing up!

            <input class="form-control FirstNameTxt" type="text" name="first_name" placeholder="*First Name"
                   autofocus="">

            <input class="form-control LastNameTxt" type="text" name="last_name" placeholder="*Last Name"
                   autofocus="">

            <input class="form-control EmailTxt" type="email" name="email" placeholder="*Email"
                   autofocus="">

            <button class="btn btn-primary btn-block button-submit" type="button">SIGN-UP</button>

</form>

The jQuery + AJAX:

;(function ($) {
    $(document).ready(function () {
        var FirstName = $('.FirstNameTxt');
        var LastName = $('.LastNameTxt');
        var EmailAddress = $('.EmailTxt');
        var successMessage = $('.success');
        var error = $('.errors-container');
        var submitbtn = $('.button-submit');
        var SubmitProgress = $('img.progress');

        var formdata = {};
        submitbtn.click(function (e) {
            resetErrors();
            postForm();
        });

        function resetErrors() {
            $('.signupForm input').removeClass('error-field');
        }

        function postForm() {
            $.each($('.signupForm input'), function(i, v) {
                if (v.type !== 'submit') {
                    formdata[v.name] = v.value;
                }
            });

            submitbtn.hide();
            error.hide();
            SubmitProgress.show();

            $.ajax({
                type: "POST",
                data: formdata,
                url: 'submission.php',
                dataType: "json"
            }).done(function (response) {
                submitbtn.show();
                SubmitProgress.hide();
                console.log("here");
                for (var i = 0; i < response.length; i++) {
                   var status = response[i].status;
                   var field = response[i].field;
                   if (status == "error") {
                     error.show();
                     $('input[name="' + field + '"]').addClass('error-field');
                   }
                    else if (status == "success") {
                        $('signupForm')[0].reset();
                        $('.form-field-content').hide();
                        successMessage.show();
                        $('.button-submit').html("Submitted");
                    }
                }
            });
        }
    });
}(jQuery));

The php code that handles the form:

$firstname = $_POST['first_name'];
$lastname = $_POST['last_name'];
$emailfield = $_POST['email'];

$return = [];

if($firstname == ""){
    $validatonStatus = "error";
    $errorField = "first_name";
}
else if($lastname == ""){
    $validatonStatus = "error";
    $errorField = "last_name";
}
else if($emailfield == "" || !filter_var($emailfield, FILTER_VALIDATE_EMAIL)){
    $validatonStatus = "error";
    $errorField = "email";
}
else {
    $validatonStatus = "success";
    $errorField = "";
   //send email notification

}
$return[] = array(
    "status" => $validatonStatus,
    "field" => $errorField,
);

echo (json_encode($return));

Body:
The PHP code just returns an array with one element, not an element for each field. It needs to add a separate element to $return for each field.

It also shouldn't be using elseif, that prevents it from validating other fields when one is invalid.

if ($firstname == "") {
    $return[] = array('status' => 'error', 'field' => 'first_name');
} else {
    $return[] = array('status' => 'success', 'field' => 'first_name');
}

if ($lastname == "") {
    $return[] = array('status' => 'error', 'field' => 'last_name');
} else {
    $return[] = array('status' => 'success', 'field' => 'last_name');
}

if($emailfield == "" || !filter_var($emailfield, FILTER_VALIDATE_EMAIL)){
    $return[] = array('status' => 'error', 'field' => 'email');
} else {
    $return[] = array('status' => 'success', 'field' => 'email');
}


答:
The problem here is fact a minor mistake. Thanks to @Asad Saeeduddin, when I try to use print cursor._last_executed to check what has happened. I found that what is in fact executed is
SELECT * FROM articles WHERE 'title' LIKE '%steven%', look the quotation mark around the title, that's the reason why I got empty set.
So always remember the string after formatting will have a quotation around

Title: Could not format sql correctly in pymysql

Body:
What I want is execute the sql
select * from articles where author like "%steven%".

For the sake of safety, i used like this way :

cursor.execute('select * from articles where %s like %s', ('author', '%steven%')

Then the result is just empty, not get a syntax error, but just empty set.
But I am pretty sure there is some thing inside, I can get result use the first sql. Is there anything run with my code ?


问:
Javascript synchronous loop in browser
Trying to automate a task in the browser with Greasemonkey.

Requirement: load a web page which contains a table displaying 15 out of 340+ results, with button controls to see the next page worth of results, go back, go to the end and so forth.

Collect the first 15 results --> got this working

Click on the 'Next' button  --> got this working

Wait until the page loads the next set of results --> dont know how

Repeat until the next button is disabled --> got this working

Cant show pictures cuz its a corporate app.

So far if I loop with setTimeouts, the timeouts get queued up and executed at the same time I think. Instead, the requirement is for the code to run the info collection, click next, wait, then collect info again.

答:
Thanks people, found this post to be the best answer
Synchronous setTimeout + Loop

This way the page loads, the first values are read, the next button is clicked, next results appear and are read, until the last page.

Thanks again for the input and ideas

Title: Javascript synchronous loop in browser


问:
What is the best practise for providing a method/class/component that supports cancellation?
How do you design a method/class that should support cancellation of the operation?

I realized that I never do that in a consistent manner and I want to change that.

Some of the things I have used:

a boolean property on the class IsCancelled that I synchronize internally. sometimes I have a CanCancel property if the operation cannot be canceled at any given time

pass a Func< bool > delegate that I repeatedly call to see if the operation has been canceled.

terminate the thread manually - although this is definitely bad practise

How do you normally do that?

答: Go back to the use case: what is the behavior you're trying to provide?  If you have an asynchronous operation that you want to cancel, then you probably can best implement a method that lets you notify the other threadt via a flag or a semaphore.  Sending a signal is a nice method to get it's attention, although I haven't looked into C#'s handling of signals.  If you need to be able to cancel and undo, the Command pattern comes in handy.</p>

OwnerDisplayName: Patrick Klug

OwnerDisplayName: Charlie Martin