问:
vb net 2017 error when reading xml file
I created a program were I get xml reponses from google maps. Everything went fine, the respose is OK, I can proper write the xml file, and I can read a specific xml node as well, exept if there is some special character in the xml file. In my case when there is an " ë " in "België" in the file.

What can be done, to be able to read xml files with these type of characters in it. Changing the " ë " in " e " can be a solution, but there will other characters giving this issue as well. I'm looking for a solution so I can use the original response from google.

Thanks a lot

my code looks as follows

write the file

```<code>    WriteXMLResponseFile(strResult)
</code>```

read specific node

```<code>    strStatus = ReadXMLData("/DistanceMatrixResponse/status")
</code>```

de code for writing and reading

```<code>Public Sub WriteXMLResponseFile(ByVal responseData As String, Optional ByVal fileName As String = "\Data\Response.xml")
    Dim intFileNr As Integer
    intFileNr = FreeFile()
    Try
        FileOpen(intFileNr, Application.StartupPath & fileName, OpenMode.Output)
        PrintLine(intFileNr, responseData)
    Catch ex As Exception
        MessageBox.Show("The file :" & vbCrLf & Application.StartupPath & fileName & vbCrLf & "does not exist", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
    End Try
    FileClose(intFileNr)
End Sub

Function ReadXMLData(ByVal dataNode As String, Optional ByVal fileName As String = "\Data\Response.xml") As String

    Dim xDoc As XmlDocument = New XmlDocument()

    Try
        xDoc.Load(Application.StartupPath & fileName)
        ReadXMLData = xDoc.SelectSingleNode(dataNode).InnerText
    Catch ex As Exception
        MsgBox(ex.Message)

    End Try

End Function
</code>```

The XML file looks as follows

```<code><?xml version="1.0" encoding="UTF-8"?>
<DistanceMatrixResponse>
 <status>OK</status>
 <origin_address>Henleykaai, 9000 Gent, Belgi뼯origin_address>
 <destination_address>Nieuwstraat, 1000 Brussel, Belgi뼯destination_address>
 <row>
  <element>
   <status>OK</status>
   <duration>
    <value>2709</value>
    <text>45 min.</text>
   </duration>
   <distance>
    <value>54752</value>
    <text>54,8 km</text>
   </distance>
   <duration_in_traffic>
    <value>2504</value>
    <text>42 min.</text>
   </duration_in_traffic>
  </element>
 </row>
</DistanceMatrixResponse>
</code>```

答:
Are you certain the issue is in reading the file and where are you seeing the characters improperly?

My theory is the issue lies with your calls to PrintLine (which is how I write to files in VB6 - but it's deprecated).

Try this instead,

```<code>Public Sub WriteXMLResponseFile(ByVal responseData As String, Optional ByVal fileName As String = "\Data\Response.xml")
    Dim intFileNr As Integer
    intFileNr = FreeFile()
    Try
        'FileOpen(intFileNr, Application.StartupPath & fileName, OpenMode.Output)
           'PrintLine(intFileNr, responseData)
        Dim writer As StreamWriter = File.CreateText("C:\TestOutputPath.txt")
         writer.WriteLine(responseData)
         writer.Close
    Catch ex As Exception
        MessageBox.Show("The file :" & vbCrLf & Application.StartupPath & fileName & vbCrLf & "does not exist", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
    End Try
    FileClose(intFileNr)
End Sub
</code>```

With this change, checkout "C:\TestOutputPath.txt" in an advanced editor as Notepad will goof up those characters too.

Title: vb net 2017 error when reading xml file

Body:
I created a program were I get xml reponses from google maps. Everything went fine, the respose is OK, I can proper write the xml file, and I can read a specific xml node as well, exept if there is some special character in the xml file. In my case when there is an " ë " in "België" in the file.

What can be done, to be able to read xml files with these type of characters in it. Changing the " ë " in " e " can be a solution, but there will other characters giving this issue as well. I'm looking for a solution so I can use the original response from google.

Thanks a lot

my code looks as follows

write the file

    WriteXMLResponseFile(strResult)

read specific node

    strStatus = ReadXMLData("/DistanceMatrixResponse/status")

de code for writing and reading

Public Sub WriteXMLResponseFile(ByVal responseData As String, Optional ByVal fileName As String = "\Data\Response.xml")
    Dim intFileNr As Integer
    intFileNr = FreeFile()
    Try
        FileOpen(intFileNr, Application.StartupPath & fileName, OpenMode.Output)
        PrintLine(intFileNr, responseData)
    Catch ex As Exception
        MessageBox.Show("The file :" & vbCrLf & Application.StartupPath & fileName & vbCrLf & "does not exist", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
    End Try
    FileClose(intFileNr)
End Sub

Function ReadXMLData(ByVal dataNode As String, Optional ByVal fileName As String = "\Data\Response.xml") As String

    Dim xDoc As XmlDocument = New XmlDocument()

    Try
        xDoc.Load(Application.StartupPath & fileName)
        ReadXMLData = xDoc.SelectSingleNode(dataNode).InnerText
    Catch ex As Exception
        MsgBox(ex.Message)

    End Try

End Function

The XML file looks as follows

<?xml version="1.0" encoding="UTF-8"?>
<DistanceMatrixResponse>
 <status>OK</status>
 <origin_address>Henleykaai, 9000 Gent, Belgi뼯origin_address>
 <destination_address>Nieuwstraat, 1000 Brussel, Belgi뼯destination_address>
 <row>
  <element>
   <status>OK</status>
   <duration>
    <value>2709</value>
    <text>45 min.</text>
   </duration>
   <distance>
    <value>54752</value>
    <text>54,8 km</text>
   </distance>
   <duration_in_traffic>
    <value>2504</value>
    <text>42 min.</text>
   </duration_in_traffic>
  </element>
 </row>
</DistanceMatrixResponse>

Body:
Are you certain the issue is in reading the file and where are you seeing the characters improperly?

My theory is the issue lies with your calls to PrintLine (which is how I write to files in VB6 - but it's deprecated).

Try this instead,

Public Sub WriteXMLResponseFile(ByVal responseData As String, Optional ByVal fileName As String = "\Data\Response.xml")
    Dim intFileNr As Integer
    intFileNr = FreeFile()
    Try
        'FileOpen(intFileNr, Application.StartupPath & fileName, OpenMode.Output)
           'PrintLine(intFileNr, responseData)
        Dim writer As StreamWriter = File.CreateText("C:\TestOutputPath.txt")
         writer.WriteLine(responseData)
         writer.Close
    Catch ex As Exception
        MessageBox.Show("The file :" & vbCrLf & Application.StartupPath & fileName & vbCrLf & "does not exist", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
    End Try
    FileClose(intFileNr)
End Sub

With this change, checkout "C:\TestOutputPath.txt" in an advanced editor as Notepad will goof up those characters too.


来源: stackexchange

问:
How do I make my React state update immediately?
The function I've made which purpose is to update state does not work perfectly.

I make a deep copy of my current state which I modify, then I set the state to that changed copy. I decided to run a simple map on the copy and update a property on each object in the array, this made the app update state immediately and show the changes. (not shown in the code below, something I just tried)

But it does not work with the modifications I truly want to make to the copy. Since the setState happens async, I understand that the changes don't happen immediately, how could I solve this? Because the changes are seen when the function is triggered a second time, but I want it to happen on the first run. You could see a live demo of what I'm building at https://non.mpedersen.me/ if you want.

Function in App.js

```<code>addressSearch(address){
    console.log('firing search for distance. Origin is: ' + address)
    let origin = [address];
    const newStores = JSON.parse(JSON.stringify(this.state.stores))
    let service = new google.maps.DistanceMatrixService();

    newStores.map(store => service.getDistanceMatrix({
      origins: origin,
      destinations: store.addressapi,
      travelMode: 'DRIVING',
    }, result => {
      store.distance = result.rows["0"].elements["0"].distance.text.replace(/\Dkm/, '').replace(/,/,'.').replace(/\s/, '');
      store.duration = result.rows["0"].elements["0"].duration.text;
    }))

    newStores.sort((a,b) => a.distance - b.distance);
    this.setState({stores : newStores})
  }
</code>```

答:
You must setState after all getDistanceMatrix are finished and your map is done. Because that function runs async, you are not really getting the function completion when you setState. The completion happens in another stack.

Promises are really good because they help dealing with scenarios like this. This is a really nice question because it shows the nature of JS mechanisms (event-loop).

Try this code but know that I haven't tested/runned it, if you get the idea it will get you to the right place:

```<code>  const getDistanceMatrix = (store) => {
    return new Promise((resolve) => {
      service.getDistanceMatrix({
        origins: origin,
        destinations: store.addressapi,
        travelMode: 'DRIVING',
      }, result => {
        store.distance = result.rows["0"].elements["0"].distance.text.replace(/\Dkm/, '').replace(/,/,'.').replace(/\s/, '');
        store.duration = result.rows["0"].elements["0"].duration.text;
        resolve(store)
      })
    })
  }

  addressSearch(address){
    console.log('firing search for distance. Origin is: ' + address)
    let origin = [address];
    const newStores = JSON.parse(JSON.stringify(this.state.stores))
    let service = new google.maps.DistanceMatrixService();

    Promise.all(newStores.map(getDistanceMatrix).then((newStores) => {
      newStores.sort((a,b) => a.distance - b.distance);
      this.setState({stores : newStores})
    })
  }
</code>```

BTW, setting state asynchronously after a Promise is resolved may lead to errors if the host component is not mounted anymore. That's actually an excellent reason to adopt a pattern like redux, it simplifies things like this a lot!

ContentLicense: CC BY-SA 3.0

Body:
The function I've made which purpose is to update state does not work perfectly.

I make a deep copy of my current state which I modify, then I set the state to that changed copy. I decided to run a simple map on the copy and update a property on each object in the array, this made the app update state immediately and show the changes. (not shown in the code below, something I just tried)

But it does not work with the modifications I truly want to make to the copy. Since the setState happens async, I understand that the changes don't happen immediately, how could I solve this? Because the changes are seen when the function is triggered a second time, but I want it to happen on the first run. You could see a live demo of what I'm building at https://non.mpedersen.me/ if you want.

Function in App.js

addressSearch(address){
    console.log('firing search for distance. Origin is: ' + address)
    let origin = [address];
    const newStores = JSON.parse(JSON.stringify(this.state.stores))
    let service = new google.maps.DistanceMatrixService();

    newStores.map(store => service.getDistanceMatrix({
      origins: origin,
      destinations: store.addressapi,
      travelMode: 'DRIVING',
    }, result => {
      store.distance = result.rows["0"].elements["0"].distance.text.replace(/\Dkm/, '').replace(/,/,'.').replace(/\s/, '');
      store.duration = result.rows["0"].elements["0"].duration.text;
    }))

    newStores.sort((a,b) => a.distance - b.distance);
    this.setState({stores : newStores})
  }

Body:
You must setState after all getDistanceMatrix are finished and your map is done. Because that function runs async, you are not really getting the function completion when you setState. The completion happens in another stack.

Promises are really good because they help dealing with scenarios like this. This is a really nice question because it shows the nature of JS mechanisms (event-loop).

Try this code but know that I haven't tested/runned it, if you get the idea it will get you to the right place:

  const getDistanceMatrix = (store) => {
    return new Promise((resolve) => {
      service.getDistanceMatrix({
        origins: origin,
        destinations: store.addressapi,
        travelMode: 'DRIVING',
      }, result => {
        store.distance = result.rows["0"].elements["0"].distance.text.replace(/\Dkm/, '').replace(/,/,'.').replace(/\s/, '');
        store.duration = result.rows["0"].elements["0"].duration.text;
        resolve(store)
      })
    })
  }

  addressSearch(address){
    console.log('firing search for distance. Origin is: ' + address)
    let origin = [address];
    const newStores = JSON.parse(JSON.stringify(this.state.stores))
    let service = new google.maps.DistanceMatrixService();

    Promise.all(newStores.map(getDistanceMatrix).then((newStores) => {
      newStores.sort((a,b) => a.distance - b.distance);
      this.setState({stores : newStores})
    })
  }

BTW, setting state asynchronously after a Promise is resolved may lead to errors if the host component is not mounted anymore. That's actually an excellent reason to adopt a pattern like redux, it simplifies things like this a lot!


问:
Sum of powers of prime factors
Given an array of integers (each <=10^6) what is the fastest way to find the sum of powers of prime factors of  each integer?</p>

```<code>Ex:-
    array: 4 6 12 7
    4 -> 2^2 -> 2
    6 -> 2^1 * 3^1 -> 1+1 -> 2
    12 -> 2^2 * 3^1 -> 2+1 -> 3
    7 -> 7^1 -> 1
    Answer: 2+2+3+1 = 8
</code>```

答:
Check this out and try to adapt something from there. Happy mathing!

```<code>// Print the number of 2s that divide n
    while (n%2 == 0)
    {
        printf("%d ", 2);
        n = n/2;
    }

    // n must be odd at this point.  So we can skip
    // one element (Note i = i +2)
    for (int i = 3; i <= sqrt(n); i = i+2)
    {
        // While i divides n, print i and divide n
        while (n%i == 0)
        {
            printf("%d ", i);
            n = n/i;
        }
    }

    // This condition is to handle the case when n
    // is a prime number greater than 2
    if (n > 2)
        printf ("%d ", n);
</code>```

You could possibly use the above algorithm on the product of all the integers in your array and obtain the same result, potentially faster due to saving time on all the add operations on the individual level.

Title: Sum of powers of prime factors

Body:
Given an array of integers (each <=10^6) what is the fastest way to find the sum of powers of prime factors of  each integer?

Ex:-
    array: 4 6 12 7
    4 -> 2^2 -> 2
    6 -> 2^1 * 3^1 -> 1+1 -> 2
    12 -> 2^2 * 3^1 -> 2+1 -> 3
    7 -> 7^1 -> 1
    Answer: 2+2+3+1 = 8

Body:
Check this out and try to adapt something from there. Happy mathing!

// Print the number of 2s that divide n
    while (n%2 == 0)
    {
        printf("%d ", 2);
        n = n/2;
    }

    // n must be odd at this point.  So we can skip
    // one element (Note i = i +2)
    for (int i = 3; i <= sqrt(n); i = i+2)
    {
        // While i divides n, print i and divide n
        while (n%i == 0)
        {
            printf("%d ", i);
            n = n/i;
        }
    }

    // This condition is to handle the case when n
    // is a prime number greater than 2
    if (n > 2)
        printf ("%d ", n);

You could possibly use the above algorithm on the product of all the integers in your array and obtain the same result, potentially faster due to saving time on all the add operations on the individual level.


问:
Supporting a design two card view and tiles grid on all mobile screen sizes
I need to design a view like below .

Explanation :

Top two views are cardviews. The top one will contain a chart
Below is 4 tiles that has an image and text at its bottom

Problem :

I am able to get an design like this but it doesnot fit in all mobiles and screen types . How can i fix this ?

Code:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#eaeaea"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".activity.MainActivity"
    tools:showIn="@layout/app_bar_main">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true">

        <LinearLayout android:id="@+id/reportView"
            android:layout_width="match_parent"
            android:layout_height="268dp"
            android:layout_marginLeft="6dp"
            android:layout_marginRight="6dp"
            android:layout_marginTop="6dp"
            android:orientation="horizontal"
            android:weightSum="1.0">

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                card_view:cardElevation="3dp"
                card_view:cardUseCompatPadding="true">

                <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    android:weightSum="1.0">

                    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical"
                        android:layout_weight="0.5"
                        android:layout_marginTop="5dp"
                        android:gravity="start">

                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:layout_gravity="start"
                            android:text="Inventory / Missing Report"
                            android:textSize="20dp"
                            android:textAlignment="center"
                            android:textColor="#4e28d8" />

                    </LinearLayout>

                    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                        android:layout_width="match_parent"
                        android:layout_height="202dp"
                        android:gravity="bottom"
                        android:orientation="vertical">

                        <com.github.mikephil.charting.charts.PieChart
                            android:id="@+id/chart"
                            android:layout_width="match_parent"
                            android:layout_height="177dp" />

                    </LinearLayout>
                </LinearLayout>
            </android.support.v7.widget.CardView>

        </LinearLayout>

        <android.support.v7.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="280dp"
            android:orientation="horizontal"
            android:layout_marginLeft="6dp"
            android:layout_marginRight="6dp"
            android:layout_gravity="bottom"
            android:weightSum="1.0">

            <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="0dip"
                    android:orientation="horizontal"
                    android:layout_weight="1" >

                    <LinearLayout
                        android:layout_height="match_parent"
                        android:layout_width="0dip"
                        android:layout_weight="1"
                        android:orientation="vertical"
                        android:padding="16dp"
                        android:paddingTop="15dp"
                        android:id="@+id/shorcut_scan">
                        <ImageView
                            android:src="@drawable/ic_scan"
                            android:layout_width="70dp"
                            android:layout_height="70dp"
                            android:layout_gravity="center"
                            android:id="@+id/shorcut_scan_image"/>
                        <TextView
                            android:id="@+id/shorcut_scan_txt"
                            android:layout_height="wrap_content"
                            android:layout_width="wrap_content"
                            android:text="Scan"
                            android:layout_gravity="center"/>
                    </LinearLayout>

                    <LinearLayout
                        android:layout_height="match_parent"
                        android:layout_width="0dip"
                        android:layout_weight="1"
                        android:orientation="vertical"
                        android:padding="16dp"
                        android:paddingTop="15dp"
                        android:id="@+id/shorcut_search">
                        <ImageView
                            android:src="@android:drawable/ic_menu_search"
                            android:layout_width="70dp"
                            android:layout_height="70dp"
                            android:layout_gravity="center"
                            android:id="@+id/shorcut_search_image"/>
                        <TextView
                            android:id="@+id/shorcut_search_txt"
                            android:layout_height="wrap_content"
                            android:layout_width="wrap_content"
                            android:text="Search"
                            android:layout_gravity="center"/>
                    </LinearLayout>

                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="0dip"
                    android:orientation="horizontal"
                    android:layout_weight="1" >

                    <LinearLayout
                        android:layout_height="match_parent"
                        android:layout_width="0dip"
                        android:layout_weight="1"
                        android:orientation="vertical"
                        android:padding="16dp"
                        android:paddingTop="15dp"
                        android:id="@+id/shorcut_assign_tags">
                        <ImageView
                            android:src="@drawable/ic_assign_tag"
                            android:layout_width="70dp"
                            android:layout_height="70dp"
                            android:layout_gravity="center"
                            android:id="@+id/shorcut_assign_tags_image"/>
                        <TextView
                            android:id="@+id/shorcut_assign_tags_txt"
                            android:layout_height="wrap_content"
                            android:layout_width="wrap_content"
                            android:text="Assign"
                            android:layout_gravity="center"/>
                    </LinearLayout>

                    <LinearLayout
                        android:layout_height="match_parent"
                        android:layout_width="0dip"
                        android:layout_weight="1"
                        android:orientation="vertical"
                        android:padding="16dp"
                        android:paddingTop="15dp"
                        android:id="@+id/shorcut_edit_tags">
                        <ImageView
                            android:src="@drawable/ic_assign_tag"
                            android:layout_width="70dp"
                            android:layout_height="70dp"
                            android:layout_gravity="center"
                            android:id="@+id/shorcut_edit_tags_image"/>
                        <TextView
                            android:id="@+id/shorcut_edit_tags_txt"
                            android:layout_height="wrap_content"
                            android:layout_width="wrap_content"
                            android:text="Edit"
                            android:layout_gravity="center"/>
                    </LinearLayout>

                </LinearLayout>
            </LinearLayout>

        </android.support.v7.widget.CardView>
    </FrameLayout>
</RelativeLayout>
</code>```

答:
You should you use constraint Layout. This layout helps you to design layouts which cover all devices. With this you can build responsive layouts.

Take this tutorial

https://developer.android.com/training/constraint-layout/index.html

Body:
I need to design a view like below .

Explanation :

Top two views are cardviews. The top one will contain a chart
Below is 4 tiles that has an image and text at its bottom

Problem :

I am able to get an design like this but it doesnot fit in all mobiles and screen types . How can i fix this ?

Code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#eaeaea"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".activity.MainActivity"
    tools:showIn="@layout/app_bar_main">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true">

        <LinearLayout android:id="@+id/reportView"
            android:layout_width="match_parent"
            android:layout_height="268dp"
            android:layout_marginLeft="6dp"
            android:layout_marginRight="6dp"
            android:layout_marginTop="6dp"
            android:orientation="horizontal"
            android:weightSum="1.0">

            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                card_view:cardElevation="3dp"
                card_view:cardUseCompatPadding="true">

                <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    android:weightSum="1.0">

                    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical"
                        android:layout_weight="0.5"
                        android:layout_marginTop="5dp"
                        android:gravity="start">

                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:layout_gravity="start"
                            android:text="Inventory / Missing Report"
                            android:textSize="20dp"
                            android:textAlignment="center"
                            android:textColor="#4e28d8" />

                    </LinearLayout>

                    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                        android:layout_width="match_parent"
                        android:layout_height="202dp"
                        android:gravity="bottom"
                        android:orientation="vertical">

                        <com.github.mikephil.charting.charts.PieChart
                            android:id="@+id/chart"
                            android:layout_width="match_parent"
                            android:layout_height="177dp" />

                    </LinearLayout>
                </LinearLayout>
            </android.support.v7.widget.CardView>

        </LinearLayout>

        <android.support.v7.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="280dp"
            android:orientation="horizontal"
            android:layout_marginLeft="6dp"
            android:layout_marginRight="6dp"
            android:layout_gravity="bottom"
            android:weightSum="1.0">

            <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="0dip"
                    android:orientation="horizontal"
                    android:layout_weight="1" >

                    <LinearLayout
                        android:layout_height="match_parent"
                        android:layout_width="0dip"
                        android:layout_weight="1"
                        android:orientation="vertical"
                        android:padding="16dp"
                        android:paddingTop="15dp"
                        android:id="@+id/shorcut_scan">
                        <ImageView
                            android:src="@drawable/ic_scan"
                            android:layout_width="70dp"
                            android:layout_height="70dp"
                            android:layout_gravity="center"
                            android:id="@+id/shorcut_scan_image"/>
                        <TextView
                            android:id="@+id/shorcut_scan_txt"
                            android:layout_height="wrap_content"
                            android:layout_width="wrap_content"
                            android:text="Scan"
                            android:layout_gravity="center"/>
                    </LinearLayout>

                    <LinearLayout
                        android:layout_height="match_parent"
                        android:layout_width="0dip"
                        android:layout_weight="1"
                        android:orientation="vertical"
                        android:padding="16dp"
                        android:paddingTop="15dp"
                        android:id="@+id/shorcut_search">
                        <ImageView
                            android:src="@android:drawable/ic_menu_search"
                            android:layout_width="70dp"
                            android:layout_height="70dp"
                            android:layout_gravity="center"
                            android:id="@+id/shorcut_search_image"/>
                        <TextView
                            android:id="@+id/shorcut_search_txt"
                            android:layout_height="wrap_content"
                            android:layout_width="wrap_content"
                            android:text="Search"
                            android:layout_gravity="center"/>
                    </LinearLayout>

                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="0dip"
                    android:orientation="horizontal"
                    android:layout_weight="1" >

                    <LinearLayout
                        android:layout_height="match_parent"
                        android:layout_width="0dip"
                        android:layout_weight="1"
                        android:orientation="vertical"
                        android:padding="16dp"
                        android:paddingTop="15dp"
                        android:id="@+id/shorcut_assign_tags">
                        <ImageView
                            android:src="@drawable/ic_assign_tag"
                            android:layout_width="70dp"
                            android:layout_height="70dp"
                            android:layout_gravity="center"
                            android:id="@+id/shorcut_assign_tags_image"/>
                        <TextView
                            android:id="@+id/shorcut_assign_tags_txt"
                            android:layout_height="wrap_content"
                            android:layout_width="wrap_content"
                            android:text="Assign"
                            android:layout_gravity="center"/>
                    </LinearLayout>

                    <LinearLayout
                        android:layout_height="match_parent"
                        android:layout_width="0dip"
                        android:layout_weight="1"
                        android:orientation="vertical"
                        android:padding="16dp"
                        android:paddingTop="15dp"
                        android:id="@+id/shorcut_edit_tags">
                        <ImageView
                            android:src="@drawable/ic_assign_tag"
                            android:layout_width="70dp"
                            android:layout_height="70dp"
                            android:layout_gravity="center"
                            android:id="@+id/shorcut_edit_tags_image"/>
                        <TextView
                            android:id="@+id/shorcut_edit_tags_txt"
                            android:layout_height="wrap_content"
                            android:layout_width="wrap_content"
                            android:text="Edit"
                            android:layout_gravity="center"/>
                    </LinearLayout>

                </LinearLayout>
            </LinearLayout>

        </android.support.v7.widget.CardView>
    </FrameLayout>
</RelativeLayout>


问:
how to use Simple Injector to Azure Worker Role
I referenced several documents but I need correct implementation to do it correctly.

References

Unity to Worker Role: https://alexandrebrisebois.wordpress.com/2013/04/14/building-windows-azure-services-without-compromising-testability/

SimpleInjector for Console app:  http://simpleinjector.readthedocs.io/en/latest/consoleintegration.html

My questions

Reference-1, Unity use using (var uc = new UnityContainer()){...} but SimpleInjector has ThreadScopedLifestyle or AsyncScopedLifestyle. Which one do I use?

Reference-2 has static Main class, static readonly Container, and static contructor. Do I define static Container for Worker role? what about static constructor for dependency registration?

I implemented as below My Implementation section. Is this code implemented correctly?

Reference Code

Reference 1;

```<code>static class Program
{
    static readonly Container container;

    static Program()
    {
        container = new Container();

        container.Register<IUserRepository, SqlUserRepository>();
        container.Register<MyRootType>();

        container.Verify();
    }

    static void Main()
    {
        var service = container.GetInstance<MyRootType>();
        service.DoSomething();
    }
}
</code>```

Reference 2;

```<code>public class WorkerRole : RoleEntryPoint
{
 public override void Run()
 {
     // This is a sample worker implementation. Replace with your logic.
     Trace.WriteLine("Worker entry point called", "Information");

     using (var uc = new UnityContainer())
     {
         uc.RegisterType<ILogger, TableStorageLogger>();
         uc.RegisterType<IEnumerable<IMessageHandler>, IMessageHandler[]>();

         var processor = uc.Resolve<MessageProcessor>();

         while (true)
         {
             processor.Process();
             Thread.Sleep(10000);
             Trace.WriteLine("Working", "Information");
         }
     }
 }
</code>```

My Implementation

I thought (1) Container could be enough to be static, (2) OnStart is good place to register services, and (3) I intended service instances are created and disposed per each loop.

```<code>public class WorkerRole : RoleEntryPoint
{
    static readonly Container container = new Container();

    public override void Run()
    {
        while (true)
        {
            using (ThreadScopedLifestyle.BeginScope(container))
            {
                var service = container.GetInstance<SomeService>();
                service.DoSomething();
            }
        }
    }

    public override bool OnStart(){
        // define.
        container.Register<SomeService>();
        container.Register<ProcessRecorderSetting>();
        container.Verify();
    }
}
</code>```

Note: I don't know above code is working.

答:
Reference-1, Unity use using (var uc = new UnityContainer()){...} but SimpleInjector has ThreadScopedLifestyle or AsyncScopedLifestyle. Which one do I use?

If I'm not mistaken, an Azure Worker Role is a short-lived application, that gets kicked off to do one simple thing and than dies quickly, just like you would with a Console Application.

Considering DI, this makes the development of a Worker Role very similar to that of a Console application. This means:

The application is short-lived

Will only run one request (compared to running multiple requests in parallel as happens with web services/applications)

There is a limit set of dependencies that need to be registered.

What this means is that, since the application is single-threaded and short-lived, there is no need to use a scoped lifestyle (such as ThreadScopedLifestyle or AsyncScopedLifestyle). Instead you could easily register all dependencies as singleton, resolve the root, call its method, and dispose the container.

If however, your application lives for a long time, and goes on in an endless loop, you typically want to simulate the notion of a 'request'. This typically means that every loop is a request, and during that request you resolve from the container. Note that you only need a scoped lifestyle if you actually have scoped registrations. If not, you don't have to wrap the request in a scope. If you have scoped registrations, you'll have to wrap each request in a scope, just as you did in your example.

Reference-2 has static Main class, static readonly Container, and static contructor. Do I define static Container for Worker role? what about static constructor for dependency registration?

Although static constructors give thread-safety and singleton behavior for free, they do however complicate debugging in case an exception is thrown, since the real error is wrapped in a TypeInitializationException. Your cctor however does make it easy to initialize your static Container field. It's fine to have the Container in a static field.

However, since these types of applications are really small with only a small set of Dependencies, do container to not use a DI Container at all. Instead use Pure DI. This might sound like a strange advice from someone who develops and maintains a DI Container, but I found it more practical to use Pure DI for small applications, especially when everything your register is singleton anyway. The advantages are:

You have compile-time support over the construction of your object graph

It prevents having to use a third party tool

There is a lot of overhead with DI Containers when it comes to the application's initialization phase, while Worker Roles should start up quickly.

Can be considerably easier for small object graphs.

Body:
I referenced several documents but I need correct implementation to do it correctly.

References

Unity to Worker Role: https://alexandrebrisebois.wordpress.com/2013/04/14/building-windows-azure-services-without-compromising-testability/

SimpleInjector for Console app:  http://simpleinjector.readthedocs.io/en/latest/consoleintegration.html

My questions

Reference-1, Unity use using (var uc = new UnityContainer()){...} but SimpleInjector has ThreadScopedLifestyle or AsyncScopedLifestyle. Which one do I use?

Reference-2 has static Main class, static readonly Container, and static contructor. Do I define static Container for Worker role? what about static constructor for dependency registration?

I implemented as below My Implementation section. Is this code implemented correctly?

Reference Code

Reference 1;

static class Program
{
    static readonly Container container;

    static Program()
    {
        container = new Container();

        container.Register<IUserRepository, SqlUserRepository>();
        container.Register<MyRootType>();

        container.Verify();
    }

    static void Main()
    {
        var service = container.GetInstance<MyRootType>();
        service.DoSomething();
    }
}

Reference 2;

public class WorkerRole : RoleEntryPoint
{
 public override void Run()
 {
     // This is a sample worker implementation. Replace with your logic.
     Trace.WriteLine("Worker entry point called", "Information");

     using (var uc = new UnityContainer())
     {
         uc.RegisterType<ILogger, TableStorageLogger>();
         uc.RegisterType<IEnumerable<IMessageHandler>, IMessageHandler[]>();

         var processor = uc.Resolve<MessageProcessor>();

         while (true)
         {
             processor.Process();
             Thread.Sleep(10000);
             Trace.WriteLine("Working", "Information");
         }
     }
 }

My Implementation

I thought (1) Container could be enough to be static, (2) OnStart is good place to register services, and (3) I intended service instances are created and disposed per each loop.

public class WorkerRole : RoleEntryPoint
{
    static readonly Container container = new Container();

    public override void Run()
    {
        while (true)
        {
            using (ThreadScopedLifestyle.BeginScope(container))
            {
                var service = container.GetInstance<SomeService>();
                service.DoSomething();
            }
        }
    }

    public override bool OnStart(){
        // define.
        container.Register<SomeService>();
        container.Register<ProcessRecorderSetting>();
        container.Verify();
    }
}

Note: I don't know above code is working.


问:
how to get rid of exceed matrix dimension (binning data)?
```<code>bet{j,3} = react{j};
numBins = {};
edges = linspace(min(bet{j,3}), max(bet{j,3}), numBins(bet{j,3}));
[N, whichBin] = histc(bet{j,3}, edges);
binsize = NaN*zeros(size(bins));

for k = 1:numBins
       bin = find(whichBin == k);
       binMembers = bet{j,3}(bin);
    if (~isempty(bin))
       mu(k) = mean(y(bin));
    end
end
</code>```

error on
edges = linspace(min(bet{j,3}), max(bet{j,3}), numBins(bet{j,3})); that says it exceeds matrix dimensions
 Any suggestions to what could be the problem, as well as suggestions if this is code might work for binning data (e.g., reaction time)?

答: Your line numBins = {}; creates an empty cell array. But in numBins(bet{j,3})); you are trying to access an element. As there is none it fails on index exceeds matrix dimension.

Body:
bet{j,3} = react{j};
numBins = {};
edges = linspace(min(bet{j,3}), max(bet{j,3}), numBins(bet{j,3}));
[N, whichBin] = histc(bet{j,3}, edges);
binsize = NaN*zeros(size(bins));

for k = 1:numBins
       bin = find(whichBin == k);
       binMembers = bet{j,3}(bin);
    if (~isempty(bin))
       mu(k) = mean(y(bin));
    end
end

error on
edges = linspace(min(bet{j,3}), max(bet{j,3}), numBins(bet{j,3})); that says it exceeds matrix dimensions
 Any suggestions to what could be the problem, as well as suggestions if this is code might work for binning data (e.g., reaction time)?


问:
C If statement Error: exited with non-zero status
I'm new to c, and I am trying to make a typing game.But the if statement doesn't work,and the output is "exited with non-zero status".May be the problem is cause by the IDE,I can't figure it out,thanks.</p>

```<code>#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main (void)
{
  char start;
  printf ("here is a typing game\n");
  printf ("type any key to start\n");
  scanf ("%c", &start);
  void game()
  {
    int i;
    char answer;
    char type[20];
    {
      for (i = 0; i < 20; i++)
      {
        printf ("%c", 'a' + (random() % 26));
      }
    }
    scanf ("%s", answer);
    if (strcmp(answer,type) == 0)
    {
      printf ("good\n");
    }
    else
    {
      printf ("so bad\n");
    }
  }
  game();
}
</code>```

答:
There are a number of things wrong with this code.

You can't have a function inside another function (as you have with game defined in main).

answer is a single char, not a string, so to read it with scanf you need to use the line scanf("%c", &answer); - if what you wanted was to read a single character, that is; from the rest of your code it seems you intended for answer to be a string, so you'd have to declare answer to be a char [20] array and call scanf with the "%s" format specifier.

You can't use strcmp to compare a char to a string. strcmp is for comparing strings to strings, not strings to characters or characters to characters. Furthermore, you never assign a string to the array type anywhere in your code.

Body:
I'm new to c, and I am trying to make a typing game.But the if statement doesn't work,and the output is "exited with non-zero status".May be the problem is cause by the IDE,I can't figure it out,thanks.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main (void)
{
  char start;
  printf ("here is a typing game\n");
  printf ("type any key to start\n");
  scanf ("%c", &start);
  void game()
  {
    int i;
    char answer;
    char type[20];
    {
      for (i = 0; i < 20; i++)
      {
        printf ("%c", 'a' + (random() % 26));
      }
    }
    scanf ("%s", answer);
    if (strcmp(answer,type) == 0)
    {
      printf ("good\n");
    }
    else
    {
      printf ("so bad\n");
    }
  }
  game();
}


问:
How to make JsonGenerator pretty-print Date and DateTime values?
I'm using this method to convert any object to a json string:

```<code>private String objectToJson(Object object) throws IOException {
        // write JSON
        StringWriter writer = new StringWriter();
        ObjectMapper mapper = new ObjectMapper();
        final JsonGenerator jsonGenerator = mapper.getJsonFactory().createJsonGenerator(writer);
        jsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter());

        mapper.writeValue(jsonGenerator, object);
        return writer.toString();
    }
</code>```

When the object being printed contains fields that are java.util.Date or jodatime's DateTime, the printed value is the number of milliseconds since the epoch. I would like, instead, to pretty-print them in a standard "HH:MM:SS" notation. How should I go about doing this?

答:
Because the epoch timestamp (number of milliseconds since January 1st, 1970, UTC) is the most efficient and accurate representation of the time, nearly all date and time related objects are serialized to it. You can of course overwrite it and if you want to use the format mentioned in the question, you'd need to add the following to your code:

```<code>DateFormat myDateFormat = new SimpleDateFormat("hh:mm:ss");
objectMapper.getSerializationConfig().setDateFormat(myDateFormat);
objectMapper.getDeserializationConfig().setDateFormat(myDateFormat);
</code>```

For more information regarding dates and times in the Jackson JSON-processor see the following link: http://wiki.fasterxml.com/JacksonFAQDateHandling

ContentLicense: CC BY-SA 2.5

Body:
I'm using this method to convert any object to a json string:

private String objectToJson(Object object) throws IOException {
        // write JSON
        StringWriter writer = new StringWriter();
        ObjectMapper mapper = new ObjectMapper();
        final JsonGenerator jsonGenerator = mapper.getJsonFactory().createJsonGenerator(writer);
        jsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter());

        mapper.writeValue(jsonGenerator, object);
        return writer.toString();
    }

When the object being printed contains fields that are java.util.Date or jodatime's DateTime, the printed value is the number of milliseconds since the epoch. I would like, instead, to pretty-print them in a standard "HH:MM:SS" notation. How should I go about doing this?

Body:
Because the epoch timestamp (number of milliseconds since January 1st, 1970, UTC) is the most efficient and accurate representation of the time, nearly all date and time related objects are serialized to it. You can of course overwrite it and if you want to use the format mentioned in the question, you'd need to add the following to your code:

DateFormat myDateFormat = new SimpleDateFormat("hh:mm:ss");
objectMapper.getSerializationConfig().setDateFormat(myDateFormat);
objectMapper.getDeserializationConfig().setDateFormat(myDateFormat);

For more information regarding dates and times in the Jackson JSON-processor see the following link: http://wiki.fasterxml.com/JacksonFAQDateHandling


问:
Which Ubuntu distribution version support GLES3
I build the cobalt with platform "linux-x64x11" on Ubuntu as below：

```<code>$cat /proc/version
Linux version 3.13.0-119-generic (buildd@lcy01-08) (gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3) ) #166-Ubuntu SMP Wed May 3 12:18:55 UTC 2017
</code>```

But this Ubuntu can't not support GLES3 because coredump happens, I have to modify the src/starboard/linux/shared/gyp_configuration.gypi file, and substitute "system_gles3" with "system_gles2" to make Cobalt run successfully.

May I ask which linux distribution version support GLES3 perfectly? Otherwise I have to upgrade my opengles library in this Ubuntu.

Wait for help, thanks,

Jenson.

答:
What is your Cobalt version? My up-to-date Cobalt on Linux falls back to GLES2 gracefully.

It looks Ubuntu 17.04 official repository does not have GLES3 yet. If you want to use GLES3, you need to manually install it. Or set the "gl_type" to "system_gles2". I recommend the latter.

Body:
I build the cobalt with platform "linux-x64x11" on Ubuntu as below：

$cat /proc/version
Linux version 3.13.0-119-generic (buildd@lcy01-08) (gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3) ) #166-Ubuntu SMP Wed May 3 12:18:55 UTC 2017

But this Ubuntu can't not support GLES3 because coredump happens, I have to modify the src/starboard/linux/shared/gyp_configuration.gypi file, and substitute "system_gles3" with "system_gles2" to make Cobalt run successfully.

May I ask which linux distribution version support GLES3 perfectly? Otherwise I have to upgrade my opengles library in this Ubuntu.

Wait for help, thanks,

Jenson.


问:
Simulating phonecalls, sms, alarm or music in background when testing with Android Espresso
I am testing an app which has a registration flow and I want to test if incoming calls, sms, alarms or other notifications during this flow will create problems. I am using Espresso for UI automation.

I am new at this and have searched quite a bit but don't seem to find a one shot solution to simulate these, I found telnet for calls but I am using a physical device and did not find anything for others.

If there is a framework for simulating these, please help.
Thank you.

答:
If you are testing more than one application, as it seems from your questions where you mention calls, sms, etc. which are assumed to be handled by other applications, you should use UiAutomator instead of Espresso.

You can find more information in Testing UI for Multiple Apps

In case you want to generate those tests automatically you can take a look at culebra.dtmilano.com.


问:
cursor update in with arcpy to fill in values
I have some code from my instructor but when I run it as a script in modeler it produces an error.
Here is a piece of the code, the rest repeats but with different values for the DIST field.
This code is meant to add the "DIST" field to a feature class and fill it in based on the conditions in the UpdateCursor.</p>

```<code>#Import arcpy and standard library modules
import arcpy, sys, os

# Get feature class from argument
zoneArcSelect = sys.argv[1]

# Add DIST field to input feature class
arcpy.AddField_management(zoneArcSelect, "DIST", "SHORT")

#get rows using update cursor and conflict selection
rows = arcpy.UpdateCursor(zoneArcSelect,"(LZONE = 'O-L' AND RZONE = 'M-1') OR (RZONE = 'O-L' AND LZONE = 'M-1')")

# calculate value for DIST and update row
for row in rows:
  row.DIST = 100
  rows.updateRow(row)

#get rows using update cursor and conflict selection
rows = arcpy.UpdateCursor(zoneArcSelect,"(LZONE = 'M-1' AND RZONE = 'RPC') OR (RZONE = 'M-1' AND LZONE = 'RPC')")

# calculate value for DIST and update row
for row in rows:
  row.DIST = 200
  rows.updateRow(row)

#get rows using update cursor and conflict selection
rows = arcpy.UpdateCursor(zoneArcSelect,"(LZONE = 'M-1' AND RZONE = 'RM-1') OR (RZONE = 'M-1' AND LZONE = 'RM-1')")

# calculate value for DIST and update row
for row in rows:
  row.DIST = 200
  rows.updateRow(row)
</code>```

答: It was my own fault not the codes that when I used the addField tool in modeler I didn't call them LZONE and RZONE. So that didn't match the code which caused the problem.</p>

Body:
I have some code from my instructor but when I run it as a script in modeler it produces an error.
Here is a piece of the code, the rest repeats but with different values for the DIST field.
This code is meant to add the "DIST" field to a feature class and fill it in based on the conditions in the UpdateCursor.

#Import arcpy and standard library modules
import arcpy, sys, os

# Get feature class from argument
zoneArcSelect = sys.argv[1]

# Add DIST field to input feature class
arcpy.AddField_management(zoneArcSelect, "DIST", "SHORT")

#get rows using update cursor and conflict selection
rows = arcpy.UpdateCursor(zoneArcSelect,"(LZONE = 'O-L' AND RZONE = 'M-1') OR (RZONE = 'O-L' AND LZONE = 'M-1')")

# calculate value for DIST and update row
for row in rows:
  row.DIST = 100
  rows.updateRow(row)

#get rows using update cursor and conflict selection
rows = arcpy.UpdateCursor(zoneArcSelect,"(LZONE = 'M-1' AND RZONE = 'RPC') OR (RZONE = 'M-1' AND LZONE = 'RPC')")

# calculate value for DIST and update row
for row in rows:
  row.DIST = 200
  rows.updateRow(row)

#get rows using update cursor and conflict selection
rows = arcpy.UpdateCursor(zoneArcSelect,"(LZONE = 'M-1' AND RZONE = 'RM-1') OR (RZONE = 'M-1' AND LZONE = 'RM-1')")

# calculate value for DIST and update row
for row in rows:
  row.DIST = 200
  rows.updateRow(row)


问:
Converting pandas date column into seconds elapsed
I have a pandas dataframe of multiple columns with a column of datetime64[ns] data. Time is in HH:MM:SS format. How can I convert this column of dates into a column of seconds elapsed? Like if the time said 10:00:00 in seconds that would be 36000. The seconds should be in a float64 type format.

Example data column

Body:
New Answer

Convert your text to Timedelta

df['Origin Time(Local)'] = pd.to_timedelta(df['Origin Time(Local)'])
df['Seconds'] = df['Origin Time(Local)'].dt.total_seconds()

Old Answer

Consider the dataframe df

df = pd.DataFrame(dict(Date=pd.date_range('2017-03-01', '2017-03-02', freq='2H')))

                  Date
0  2017-03-01 00:00:00
1  2017-03-01 02:00:00
2  2017-03-01 04:00:00
3  2017-03-01 06:00:00
4  2017-03-01 08:00:00
5  2017-03-01 10:00:00
6  2017-03-01 12:00:00
7  2017-03-01 14:00:00
8  2017-03-01 16:00:00
9  2017-03-01 18:00:00
10 2017-03-01 20:00:00
11 2017-03-01 22:00:00
12 2017-03-02 00:00:00

Subtract the most recent day from the timestamps and use total_seconds.  total_seconds is an attribute of a Timedelta.  We get a series of Timedeltas by taking the difference between two series of Timestamps.

(df.Date - df.Date.dt.floor('D')).dt.total_seconds()
# equivalent to
# (df.Date - pd.to_datetime(df.Date.dt.date)).dt.total_seconds()

0         0.0
1      7200.0
2     14400.0
3     21600.0
4     28800.0
5     36000.0
6     43200.0
7     50400.0
8     57600.0
9     64800.0
10    72000.0
11    79200.0
12        0.0
Name: Date, dtype: float64

Put it in a new column

df.assign(seconds=(df.Date - df.Date.dt.floor('D')).dt.total_seconds())

                  Date  seconds
0  2017-03-01 00:00:00      0.0
1  2017-03-01 02:00:00   7200.0
2  2017-03-01 04:00:00  14400.0
3  2017-03-01 06:00:00  21600.0
4  2017-03-01 08:00:00  28800.0
5  2017-03-01 10:00:00  36000.0
6  2017-03-01 12:00:00  43200.0
7  2017-03-01 14:00:00  50400.0
8  2017-03-01 16:00:00  57600.0
9  2017-03-01 18:00:00  64800.0
10 2017-03-01 20:00:00  72000.0
11 2017-03-01 22:00:00  79200.0
12 2017-03-02 00:00:00      0.0


问:
Using plist in a DetailView
I have this tableview in my app which has a particular item name such as "Apple". When the user taps on that selected item they are directed to a detailView that views an image and description of that selected item. I was thinking to use plist´s to do this, but I don't know how to. Please help me.

I looked at some sources such as iCodeBlog but they don´t really explain retrieving and saving so well. Maybe you people can also give reference to some links that describe this better.

Heres a plist that I have tried. Each of the items (Orange, Apple) have the data that I want to display in my detailView. I basically want to display the data shown.

答:
Plists are really useful for many cases:

```<code>+ (NSMutableDictionary*) containerDictionary {

    NSString *path = [[NSBundle mainBundle] bundlePath];
    NSString *finalPath = [path stringByAppendingPathComponent:@"ContainerGraphics.plist"];
    NSMutableDictionary *plistData = [NSMutableDictionary dictionaryWithContentsOfFile:finalPath];

    return plistData;

}
</code>```

This loads a plist file (Property List) called "ContainerGraphics.plist" from my apps bundle.

The plist file is actually just an XML file. You can build one in Xcode by selecting "new file" -> "resource" -> "Property list".

You don't really say what it is you don't understand, so if there is something specific that you find hard to comprehend, please elaborate:)

EDIT:

With the plist you post, use my above approach to "load in" the plist file.
Then it is an NSDictionary of NSDictionaries..

So to get to the "Apple" dictionary you go:

```<code>NSDictionary *appleDictionary = [plistData objectForKey:@"Apple"];
</code>```

Which means something along - go into the list and retrieve the "Apple" dictionary.

Now to get the image and description values you would go:

```<code>NSString *imagePath = [appleDictionary objectForKey:@"image"];
NSString *descriptionString = [appleDictionary objectForKey:@"description"];
</code>```

That is pretty much what there is to it.

If you have a a tableView that need to be populated with this data there is a catch!
The data inside an NSDictionary has no order. So you can't just reference [dictionary objectAtIndex:indexPath.row] as you would do with an array of data for a tableView.

What you do then is to first get the plistData, as in my first example.
(do this in viewDidLoad).
Then you extract all the keys from the plistData dictionary - notice that the "top dictionary is specific, "Apple, "Orange" etc. not values you want to hardcode into your app. But, the dictionaries inside these dictionaries are general, image, description…

So:

```<code>NSArray *allKeys = [plistData allKeys];
</code>```

the allKey array now contains keys (Apple, Orange, etc.)to get to the NSDictionaries in the plistData.

In the cellForRowAtIndexPath method you can now go:

```<code>NSDictionary *dictionaryForCurrentCell = [plistData objectForKey:[allKeys objectAtIndex:indexPath.row]];
[cell.textLabel setText:[dictionaryForCurrentCell objectForKey:@"image"]];
[cell.detailLabel setText:[dictionaryForCurrentCell objectForKey:@"description"]];
</code>```

Hope it helps:)

Title: Using plist in a DetailView

Body:
Plists are really useful for many cases:

+ (NSMutableDictionary*) containerDictionary {

    NSString *path = [[NSBundle mainBundle] bundlePath];
    NSString *finalPath = [path stringByAppendingPathComponent:@"ContainerGraphics.plist"];
    NSMutableDictionary *plistData = [NSMutableDictionary dictionaryWithContentsOfFile:finalPath];

    return plistData;

}

This loads a plist file (Property List) called "ContainerGraphics.plist" from my apps bundle.

The plist file is actually just an XML file. You can build one in Xcode by selecting "new file" -> "resource" -> "Property list".

You don't really say what it is you don't understand, so if there is something specific that you find hard to comprehend, please elaborate:)

EDIT:

With the plist you post, use my above approach to "load in" the plist file.
Then it is an NSDictionary of NSDictionaries..

So to get to the "Apple" dictionary you go:

NSDictionary *appleDictionary = [plistData objectForKey:@"Apple"];

Which means something along - go into the list and retrieve the "Apple" dictionary.

Now to get the image and description values you would go:

NSString *imagePath = [appleDictionary objectForKey:@"image"];
NSString *descriptionString = [appleDictionary objectForKey:@"description"];

That is pretty much what there is to it.

If you have a a tableView that need to be populated with this data there is a catch!
The data inside an NSDictionary has no order. So you can't just reference [dictionary objectAtIndex:indexPath.row] as you would do with an array of data for a tableView.

What you do then is to first get the plistData, as in my first example.
(do this in viewDidLoad).
Then you extract all the keys from the plistData dictionary - notice that the "top dictionary is specific, "Apple, "Orange" etc. not values you want to hardcode into your app. But, the dictionaries inside these dictionaries are general, image, description…

So:

NSArray *allKeys = [plistData allKeys];

the allKey array now contains keys (Apple, Orange, etc.)to get to the NSDictionaries in the plistData.

In the cellForRowAtIndexPath method you can now go:

NSDictionary *dictionaryForCurrentCell = [plistData objectForKey:[allKeys objectAtIndex:indexPath.row]];
[cell.textLabel setText:[dictionaryForCurrentCell objectForKey:@"image"]];
[cell.detailLabel setText:[dictionaryForCurrentCell objectForKey:@"description"]];

Hope it helps:)


问:
how to store firebase snap.val() in a varible to use else where?
how would one go and store data from the firebase database using javascript. I want to use the once method so its not constantly looking up for any changes.
For example like this:

```<code>database.child('readOnly/something').once('value').then((snap) => {
        const groupObj = [
            snap.val()
        ]
    });
    app.get('/something',(req,res)=>{
            res.render('something',{
                "groupList": groupObj
            });
        });
            // Individual Life Groups
            app.get('/something/:name',(req,res)=>{
                const group = req.path.split("/").pop();
                console.log(groupObj.length)
                for (i = 0; i < groupObj.length; i+=1) {
                    if(groupObj[i].url   == group){
                        var desiredGroup = groupObj[i];
                        console.log(desiredGroup);
                        break;
                    }
                }
                res.render('group', desiredGroup);
                // To-Do: Add Data and Bindings
            });
</code>```

I am using the up to date versions of expressjs, firebase, nodejs, and npm.

答:
You could place the groupObj variable in a "global" area so all callbacks can use it.

```<code>const groupObj = [];

database.child('readOnly/something').once('value').then((snap) => {
  groupObj.push(snap.val());
});

app.get('/something',(req,res)=>{
    res.render('something',{
        "groupList": groupObj
    });
});

// Individual Life Groups
app.get('/something/:name',(req,res)=>{
    const group = req.path.split("/").pop();
    console.log(groupObj.length)
    for (i = 0; i < groupObj.length; i+=1) {
        if(groupObj[i].url   == group){
            var desiredGroup = groupObj[i];
            console.log(desiredGroup);
            break;
        }
    }
    res.render('group', desiredGroup);
    // To-Do: Add Data and Bindings
});
</code>```

Body:
how would one go and store data from the firebase database using javascript. I want to use the once method so its not constantly looking up for any changes.
For example like this:

database.child('readOnly/something').once('value').then((snap) => {
        const groupObj = [
            snap.val()
        ]
    });
    app.get('/something',(req,res)=>{
            res.render('something',{
                "groupList": groupObj
            });
        });
            // Individual Life Groups
            app.get('/something/:name',(req,res)=>{
                const group = req.path.split("/").pop();
                console.log(groupObj.length)
                for (i = 0; i < groupObj.length; i+=1) {
                    if(groupObj[i].url   == group){
                        var desiredGroup = groupObj[i];
                        console.log(desiredGroup);
                        break;
                    }
                }
                res.render('group', desiredGroup);
                // To-Do: Add Data and Bindings
            });

I am using the up to date versions of expressjs, firebase, nodejs, and npm.

Body:
You could place the groupObj variable in a "global" area so all callbacks can use it.

const groupObj = [];

database.child('readOnly/something').once('value').then((snap) => {
  groupObj.push(snap.val());
});

app.get('/something',(req,res)=>{
    res.render('something',{
        "groupList": groupObj
    });
});

// Individual Life Groups
app.get('/something/:name',(req,res)=>{
    const group = req.path.split("/").pop();
    console.log(groupObj.length)
    for (i = 0; i < groupObj.length; i+=1) {
        if(groupObj[i].url   == group){
            var desiredGroup = groupObj[i];
            console.log(desiredGroup);
            break;
        }
    }
    res.render('group', desiredGroup);
    // To-Do: Add Data and Bindings
});


问:
Setup.py attempts to import the package it is installing
UPDATE
This is a bug in the setup.py of the package

Attempting to install certain packages using pip and I get this error:

```<code>pip install saspy

command python setup.py egg_info failed with error code 1
</code>```

Upon reading the traceback I see that it failed while attempting to import saspy.This is an excerpt from the setup.py which is indeed attempting to import from saspy, while installing saspy. How is this supposed to work? I am using setuptools 36.0.1, pip 9.0.1 and (long story) python 2.7.8.

```<code>try:
  from setuptools import setup
except ImportError:
    from distutils.core import setup

from saspy import __version__

with open('README.md') as f:
    readme = f.read()
</code>```

答: This is a buggy setup.py.  It's a common mistake, since with a source installation, you can import the package from the unpacked source tree before it's been installed.</p>

Body:
UPDATE
This is a bug in the setup.py of the package

Attempting to install certain packages using pip and I get this error:

pip install saspy

command python setup.py egg_info failed with error code 1

Upon reading the traceback I see that it failed while attempting to import saspy.This is an excerpt from the setup.py which is indeed attempting to import from saspy, while installing saspy. How is this supposed to work? I am using setuptools 36.0.1, pip 9.0.1 and (long story) python 2.7.8.

try:
  from setuptools import setup
except ImportError:
    from distutils.core import setup

from saspy import __version__

with open('README.md') as f:
    readme = f.read()


问:
Return two pointers from a function in c
I know that you can return a pointer to the first element of an array in c by doing:

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

int *my_func(void);

int main(void)
{
    int *a;
    int i;

    a = my_func();

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

    free(a);

    return 0;
}

int *my_func(void)
{
    int *array;
    int i;

    array = calloc(3, sizeof(int));

    for(i = 0; i < 3; i++)
    {
        array[i] = i;
    }

    return array;
}
</code>```

But if I wanted to return two pointers instead of just one, I tried:

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

int *my_func(int *);

int main(void)
{
    int *a;
    int *b;
    int i;

    a = my_func(b);

    for(i = 0; i < 3; i++)
    {
        printf("a[%d] = %d\n", i, a[i]);
        printf("b[%d] = %d\n", i, b[i]);
    }

    free(a);
    free(b);

    return 0;
}

int *my_func(int *array2)
{
    int *array;
    int i;

    array = calloc(3, sizeof(int));
    array2 = calloc(3, sizeof(int));

    for(i = 0; i < 3; i++)
    {
        array[i] = i;
        array2[i] = i;
    }

    return array;
}
</code>```

But this seg faults on the printf for b. I ran it through valgrind and it says that there is an invalid read of size 4 at the printf for b, which means I'm doing something screwy with the b pointer. I was just wondering what the best way to "return" a second pointer to an array was in c? I'm asking because I would like to do it this way rather than use a global variable (I'm not opposed to them, as they are useful at times, I just prefer not to use them if possible). The other questions I've seen on this site used statically allocated arrays, but I haven't yet stumbled across a question that was using dynamic allocation. Thanks in advance!

答:
Function parameters are its local variables. Functions deal with copies of values of the supplied arguments.

You can imagine your function definition and its call the following way

```<code>a = my_func(b);

int *my_func( /* int *array2 */ )
{
    int *array2 = b;
    //...
}
</code>```

So any changes of the local variable array2 inside the function do not influence on the original argument b.

For such a function definition you have to pass the argument by reference that is the function should be declared like

```<code>int *my_func( int **array2 );
                  ^^
</code>```

There are many ways to implement the function. You could define a structure of two pointers as for example

```<code>struct Pair
{
    int *a;
    int *b;
};
</code>```

and use it as the return type of the function

```<code>struct Pair my_func( void );
</code>```

Another approach is to pass to the function an array of pointers to the original pointers.

The function can look as it is shown in the demonstrative program.

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

size_t multiple_alloc( int ** a[], size_t n, size_t m )
{
    for ( size_t i = 0; i < n; i++ ) *a[i] = NULL;

    size_t k = 0;

    for ( ; k < n && ( *a[k] = malloc( m * sizeof( int ) ) ) != NULL; k++ )
    {
        for ( size_t i = 0; i < m; i++ ) ( *a[k] )[i] = i;
    }

    return k;
}

#define N   2
#define M   3

int main(void)
{
    int *a;
    int *b;

    multiple_alloc( ( int ** [] ) { &a, &b }, N, M );

    if ( a )
    {
        for ( size_t i = 0; i < M; i++ ) printf( "%d ", a[i] );
        putchar( '\n' );
    }

    if ( b )
    {
        for ( size_t i = 0; i < M; i++ ) printf( "%d ", b[i] );
        putchar( '\n' );
    }

    free( a );
    free( b );

    return 0;
}
</code>```

The program output is

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

Body:
I know that you can return a pointer to the first element of an array in c by doing:

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

int *my_func(void);

int main(void)
{
    int *a;
    int i;

    a = my_func();

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

    free(a);

    return 0;
}

int *my_func(void)
{
    int *array;
    int i;

    array = calloc(3, sizeof(int));

    for(i = 0; i < 3; i++)
    {
        array[i] = i;
    }

    return array;
}

But if I wanted to return two pointers instead of just one, I tried:

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

int *my_func(int *);

int main(void)
{
    int *a;
    int *b;
    int i;

    a = my_func(b);

    for(i = 0; i < 3; i++)
    {
        printf("a[%d] = %d\n", i, a[i]);
        printf("b[%d] = %d\n", i, b[i]);
    }

    free(a);
    free(b);

    return 0;
}

int *my_func(int *array2)
{
    int *array;
    int i;

    array = calloc(3, sizeof(int));
    array2 = calloc(3, sizeof(int));

    for(i = 0; i < 3; i++)
    {
        array[i] = i;
        array2[i] = i;
    }

    return array;
}

But this seg faults on the printf for b. I ran it through valgrind and it says that there is an invalid read of size 4 at the printf for b, which means I'm doing something screwy with the b pointer. I was just wondering what the best way to "return" a second pointer to an array was in c? I'm asking because I would like to do it this way rather than use a global variable (I'm not opposed to them, as they are useful at times, I just prefer not to use them if possible). The other questions I've seen on this site used statically allocated arrays, but I haven't yet stumbled across a question that was using dynamic allocation. Thanks in advance!

Body:
Function parameters are its local variables. Functions deal with copies of values of the supplied arguments.

You can imagine your function definition and its call the following way

a = my_func(b);

int *my_func( /* int *array2 */ )
{
    int *array2 = b;
    //...
}

So any changes of the local variable array2 inside the function do not influence on the original argument b.

For such a function definition you have to pass the argument by reference that is the function should be declared like

int *my_func( int **array2 );
                  ^^

There are many ways to implement the function. You could define a structure of two pointers as for example

struct Pair
{
    int *a;
    int *b;
};

and use it as the return type of the function

struct Pair my_func( void );

Another approach is to pass to the function an array of pointers to the original pointers.

The function can look as it is shown in the demonstrative program.

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

size_t multiple_alloc( int ** a[], size_t n, size_t m )
{
    for ( size_t i = 0; i < n; i++ ) *a[i] = NULL;

    size_t k = 0;

    for ( ; k < n && ( *a[k] = malloc( m * sizeof( int ) ) ) != NULL; k++ )
    {
        for ( size_t i = 0; i < m; i++ ) ( *a[k] )[i] = i;
    }

    return k;
}

#define N   2
#define M   3

int main(void)
{
    int *a;
    int *b;

    multiple_alloc( ( int ** [] ) { &a, &b }, N, M );

    if ( a )
    {
        for ( size_t i = 0; i < M; i++ ) printf( "%d ", a[i] );
        putchar( '\n' );
    }

    if ( b )
    {
        for ( size_t i = 0; i < M; i++ ) printf( "%d ", b[i] );
        putchar( '\n' );
    }

    free( a );
    free( b );

    return 0;
}

The program output is

0 1 2
0 1 2


问:
installshield Installer deletes folder from my documents
I have two installers, one will create folder("ProjectRDE") in mydocuments using Installshield Limited Edition --> Application Files --> [PersonalFolder]. As expected when i run the exe, it created "ProjectRDE" folder in MyDocuments.
Another installer(which is also installs the same project output) will not have any folders in [PersonalFolder].(i consider the second installer as Upgrader.exe)
When i execute the second installer it deleted the "ProjectRDE" folder from MyDocuments. But i have not create any custom actions. Even I cant mark the folder as "Permanant", as the installer is only limited edition.
My query is, why this "ProjectRDE" is getting deleted, even i have not mentioned it in the second installer.</p>

答: I'm not sure I exactly understand your situation entirely, but if your "Upgrader.exe" is actually performing a major upgrade, then it triggers an uninstall of the previous version, before installing the upgrade.</p>


问:
Access upper class property for List<T> in T class C#
There are my classes:

```<code>public class myClass1
{
    public int Code { get; set; }
    public List<myItem> Items { get; set; }
}
public class myClass2
{
    public int Code { get; set; }
    public List<myItem> Items { get; set; }
}
public class myItem
{
    private void MyMethod()
    {
        int ParentClass_CodeProperty = ???
    }
}
</code>```

How to access (Code property) in upper (or Parent) class ?

example :

```<code>string ParentClass_CodeProperty = this.Parent.GetType().GetProperty("Code").GetValue(a, null).ToString()
</code>```

答:
One thing you can do is modify your MyItem class to have a ParentClassCode property, and let this get set through the constructor:

```<code>public class MyItem
{
    public int ParentClassCode { get; set; }

    public MyItem(int parentClassCode)
    {
        ParentClassCode = parentClassCode;
    }
    private void MyMethod()
    {
        // Now we can refer to ParentClassCode
    }
}
</code>```

Then you would set the parent class code on creation of a new MyItem:

```<code>MyClass1 class1 = new MyClass1();
class1.Code = 42;
class1.Items.Add(new MyItem(class1.Code));
</code>```

Another way to do this, without using the constructor, would be to create a method on the containing class that should be used to add items to the list, and in that AddItem method, set the property:

```<code>public class MyClass1
{
    public int Code { get; set; }
    public List<MyItem> Items { get; set; }

    public void AddItem(MyItem item)
    {
        if (item == null) throw new ArgumentNullException();
        item.ParentClassCode = Code;
        Items.Add(item);
    }
}
</code>```

Of course this means there's more work to do to prevent users from bypassing your AddItem method and calling MyClass1.Items.Add(item);, but you get the idea.

Body:
There are my classes:

public class myClass1
{
    public int Code { get; set; }
    public List<myItem> Items { get; set; }
}
public class myClass2
{
    public int Code { get; set; }
    public List<myItem> Items { get; set; }
}
public class myItem
{
    private void MyMethod()
    {
        int ParentClass_CodeProperty = ???
    }
}

How to access (Code property) in upper (or Parent) class ?

example :

string ParentClass_CodeProperty = this.Parent.GetType().GetProperty("Code").GetValue(a, null).ToString()

Body:
One thing you can do is modify your MyItem class to have a ParentClassCode property, and let this get set through the constructor:

public class MyItem
{
    public int ParentClassCode { get; set; }

    public MyItem(int parentClassCode)
    {
        ParentClassCode = parentClassCode;
    }
    private void MyMethod()
    {
        // Now we can refer to ParentClassCode
    }
}

Then you would set the parent class code on creation of a new MyItem:

MyClass1 class1 = new MyClass1();
class1.Code = 42;
class1.Items.Add(new MyItem(class1.Code));

Another way to do this, without using the constructor, would be to create a method on the containing class that should be used to add items to the list, and in that AddItem method, set the property:

public class MyClass1
{
    public int Code { get; set; }
    public List<MyItem> Items { get; set; }

    public void AddItem(MyItem item)
    {
        if (item == null) throw new ArgumentNullException();
        item.ParentClassCode = Code;
        Items.Add(item);
    }
}

Of course this means there's more work to do to prevent users from bypassing your AddItem method and calling MyClass1.Items.Add(item);, but you get the idea.


问:
How to implement custom paging in ASP.NET Gridview that has Command Buttons in VB.NET
I am currently trying to implement a gridview with custom paging. I've gotten this to work by following the tutorial on ASP Snippets, located here:
http://www.aspsnippets.com/Articles/ASPNet-GridView-Custom-Paging-with-PageSize-Change-Dropdown.aspx

This work well. However, I run into an issue. My gridview has template controls in it, which run code when used. For example, I have a button that, when clicked, replaces the cell contents with two different buttons. When I use the pagination technique given above, clicking on any template control (causing postback), erases my gridview. I realize that this is because I have to recreate the gridview on every postback because of the way the pagination is set up. However, when I recreate the gridview, the effects of my button are gone because it has been recreated. I'm not sure how to escape this..

Does anyone have any ideas?

For a specific pointed question,

I am looking to create a gridview with custom pagination that will allow for template controls and extended functionality.

Thank you

Generic information:

IDE: Visual Studio 2012

Language: VB.NET, ASP.NET

Database: SQL SERVER 2008 R2

答:
I fixed this issue by programmatic ally resetting the states of my controls to match what they were before post-back.

I haven't had any issues since setting that up.


问:
MVVM binding many properties
Is there a simpeler way to bind many properties?

So if you have a Person class with properties: lastname, firstname, birthday, gender, title, ...

Now I do this for every property on the ViewModel:

```<code> public string _LastName;
 public string LastName
 {
    get { return _LastName; }
    set { _LastName = value;
          RaisePropertyChanged("LastName"); }
 }
</code>```

And on the XAML page this binding:

```<code> <TextBlock Text="{Binding FirstName}" />
</code>```

Now image if Person object has like 20 properties..
So my question is can I do this in a simpeler way?

答:
If you use a third party MVVM framework, it also might have a code snippet to create property with INotifyPropertyChanged.

If you use Catel, you can download templates and snippets here:
http://catelproject.com/downloads/general-files/

And here's implementation for Caliburn.Micro:
https://github.com/winterdouglas/propc

Title: MVVM binding many properties

Body:
Is there a simpeler way to bind many properties?

So if you have a Person class with properties: lastname, firstname, birthday, gender, title, ...

Now I do this for every property on the ViewModel:

 public string _LastName;
 public string LastName
 {
    get { return _LastName; }
    set { _LastName = value;
          RaisePropertyChanged("LastName"); }
 }

And on the XAML page this binding:

 <TextBlock Text="{Binding FirstName}" />

Now image if Person object has like 20 properties..
So my question is can I do this in a simpeler way?


问:
redshift sql current_date get_date() performance issue
I would like to know whether using the current_date or get_date() function on redshift SQL would lower the query performance compared to using '2016-05-05' directly, for example.

Example 1:

select
  *
  from
  table a
  where time >= current_date - 1
  and time < current_date

Example 2:

select
  *
  from table a
  where time >='2016-05-08'
  and time < '2016-05-09'

Would example 1 or example 2 have better performance? Or would both have the same?

Hope someone could shed some light on it

答:
I just ran up against this, so I shall share my anecdotal experience:

select * from table where ts > current_date limit 20 was running for 10+mins before I got impatient and killed it.

select * from table where ts > '2017-06-08' limit 20 completed in 16s.

table has a sort key on ts, and was freshly analyzed


问:
How to format only one table with css
I'm trying to select one specific table on one html page to be formatted with css. I do not want any other tables anywhere else, including on the same page, to be formatted this way.

I tried this inside the header but it did not work-

```<code><style>
    #table3 {
        td,th { padding: 10px }
        tr:hover { background-color: #f5f5f5 }
    }
</style>

<table id="table3">
...
</table>
</code>```

答:
You can't nest selectors like that.  At least not in normal CSS.

You want:

```<code><style>
    #table3 td, #table3 th { padding: 10px }
    #table3 tr:hover { background-color: #f5f5f5 }
</style>

<table id="table3">
...
</table>
</code>```

Title: How to format only one table with css

Body:
I'm trying to select one specific table on one html page to be formatted with css. I do not want any other tables anywhere else, including on the same page, to be formatted this way.

I tried this inside the header but it did not work-

...

Body:
You can't nest selectors like that.  At least not in normal CSS.

You want:

<style>
    #table3 td, #table3 th { padding: 10px }
    #table3 tr:hover { background-color: #f5f5f5 }
</style>

<table id="table3">
...
</table>


问:
SQL find partial duplicates in table
I have a table with partial duplicate values in one of the column and that is the primary key on the table. I tried to write a query to find those duplicates and couldn't figure it out.
Ex:

```<code>Taxi(Number, id) - Number is primary key on the table
Values(123, 253)
Values(123-, 253)
Values(1 23,253)
</code>```

These all are treated as duplicates according to the requirements.
This is the query I tried with no luck

```<code>select * from taxi t where exists(
select 1 from taxi t2
where t1.id = t2.id
and t2.number like t1.number||'%')
</code>```

This is giving me all the values back. Any help is appreciated

答: you have messed up data.  Try selecting and grouping using a regular expression which removes the blank and '-' [and other characters].  any set having count(*) > 1 is a duplicate.</p>

Title: SQL find partial duplicates in table

Body:
I have a table with partial duplicate values in one of the column and that is the primary key on the table. I tried to write a query to find those duplicates and couldn't figure it out.
Ex:

Taxi(Number, id) - Number is primary key on the table
Values(123, 253)
Values(123-, 253)
Values(1 23,253)

These all are treated as duplicates according to the requirements.
This is the query I tried with no luck

select * from taxi t where exists(
select 1 from taxi t2
where t1.id = t2.id
and t2.number like t1.number||'%')

This is giving me all the values back. Any help is appreciated


答:
This wont work because this isn't the format for CSS, although the concept is right in what you have done the format isn't correct.

Try this...

```<code>#table3 td, #table3 th {
    padding: 10px;
}

#table3 tr:hover {
    background-color: #f5f5f5;
}
</code>```

However, if you would like to do it the way in which you did it. You could do it with a CSS compiler such as less, which you can view online as less js, it makes CSS lightweight and a lot easier to write.

Title: How to format only one table with css

Body:
This wont work because this isn't the format for CSS, although the concept is right in what you have done the format isn't correct.

Try this...

#table3 td, #table3 th {
    padding: 10px;
}

#table3 tr:hover {
    background-color: #f5f5f5;
}

However, if you would like to do it the way in which you did it. You could do it with a CSS compiler such as less, which you can view online as less js, it makes CSS lightweight and a lot easier to write.


问:
How to debug this WCF error?
When trying to run or reference the service project I get this error:

The type 'MyCompany.MyNameSpace.MyType', provided as  the Service attribute value in the ServiceHost directive could not be found.

Where to look to fix this?

Edit:
This is while running under the buit in vs 2008 cassini.

答: WCF, Service attribute value in the ServiceHost directive could not be found</p>

Title: How to debug this WCF error?

ContentLicense: CC BY-SA 4.0


问:
How do I run a Python program?
I used Komodo Edit 5 to write some .py files. My IDE window looks like this:

How do I actually run the .py file to test the program? I tried pressing F5 but it didn't appear to do anything.

I also tried using IDLE, but it seems like you can only run a couple of lines at a time.

答: If this helps anyone, neither "python [filename].py" or "python.exe [filename.py]" worked for me, but "start python [filename].py" did. If anyone else is experiencing issues with the former two commands, try the latter one.</p>

Title: How do I run a Python program?


问:
Bouncy Castle Decode CSR c#
I'm attempting to learn how to decode a csr with the bouncy castle as I intend to use it to learn other crypto things.

I'm also not finding any documentation for c# just java.

Here's how I'm calling DecodeCSR(string str):

```<code> static void Main(string[] args)
    {
        string csr = "-----BEGIN NEW CERTIFICATE REQUEST-----...";
        DecodeCSR(csr);
        Console.ReadLine();
    }
</code>```

Here's my method where I'm getting an IO Exception(Included below), my main problem is I don't know what to give Pkcs10CertificationRequest.

```<code>private static void DecodeCSR(string csr)
    {
        try
        {
            byte[] csrEncode = Encoding.UTF8.GetBytes(csr);
            Pkcs10CertificationRequest csrDecoder = new Pkcs10CertificationRequest(csrEncode);
            byte[] csrDecode = csrDecoder.GetEncoded();
        }
        catch (IOException e)
        {
            Console.WriteLine(e);
        }

    }
</code>```

The error message:

```<code> System.IO.IOException: unknown tag 13 encountered
   at Org.BouncyCastle.Asn1.Asn1InputStream.BuildObject(Int32 tag, Int32 tagNo, Int32 length)
   at Org.BouncyCastle.Asn1.Asn1InputStream.ReadObject()
   at Org.BouncyCastle.Asn1.Asn1Object.FromByteArray(Byte[] data)
   at Org.BouncyCastle.Pkcs.Pkcs10CertificationRequest..ctor(Byte[] encoded)
</code>```

答:
You are trying to decode the CSR into a byte array the wrong way.

Here's a test CSR I created to answer this question:

-----BEGIN NEW CERTIFICATE REQUEST-----
MIIC3zCCAccCAQAwajELMAkGA1UEBhMCWFgxEDAOBgNVBAgTB1Vua25vd24xEDAOBgNVBAcTB05v
d2hlcmUxGjAYBgNVBAoTEVRlc3RlcnMgVW5saW1pdGVkMQ0wCwYDVQQLEwRUZXN0MQwwCgYDVQQD
EwNCb2IwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCUf5kRJVMNwPu+nEnJ3Av5J59H
vkeU0fOQtI+ezvHoJXc0A4iGDBm9PUw+eAXHw237Yu7+AyzgQCD8mwQt/lHLjXG/yeX66PhTFlzH
Lhk4rqL9PQATbl4uCYtWoJmeEOWHL26dfI//AFsL9/smVyjD1mJfee6998PwwHB6BxqSaqXiR1Et
lC4jx+B2E6btvMtREQ94cECoQudSgo3MRMBH+FuEcCofNtwosEpptjIN59ywVfDDU2Me58r930Ej
A8EZbXwYpUjwaHtXK80TKq8yF3Af7Hbt6FhkXOv1QtF0EYUKvE4BVTAx4mPLUy2mct8Ft8/+/Lbt
HDmslaBCAFZrAgMBAAGgMDAuBgkqhkiG9w0BCQ4xITAfMB0GA1UdDgQWBBRt0aHvY5c29iUS6/7E
3FC+Bn3FNDANBgkqhkiG9w0BAQsFAAOCAQEAe+e+3WfxJd/ztcIDRR8YfVkeOlE0b8Erze13fQi/
GsBJQ2MF/7T8x/8ZF2CqusrmLTzb5sY5qVKlRgnguow6xnGu0QOiJdC4kgoqgAaxDwz/eIhMGkt9
hyfTkMWiMD0OfYpdhXWUHrvbzWyUNI1ouWjOoqS03LvSiT4Cq+7Xca8ETVyuBN1FZeFUxO59goqI
eKKenzPqJHcPUjkQbUBgsfKpuRXveRG+vacCt0chWUK4TEVyPzH2EDH0kiQh6dsVizKrHUihh5K/
BhZNqzyBW7G5vbxq4wBz7cLDskfqTsOnHRsAlYmNsXO2wV1LQ2f04F+FHIzZ+IWaO86cxTPMtA==
-----END NEW CERTIFICATE REQUEST-----
```

<p>To decode a CSR such as this one we need to:</p>

<ul>
<li>remove the lines <code>-----BEGIN NEW CERTIFICATE REQUEST-----</code> and <code>-----END NEW CERTIFICATE REQUEST-----</code> from the top and bottom,</li>
<li>convert the remaining characters from Base64 into a byte array.</li>
<li>pass the resulting byte array to <code>Pkcs10CertificateRequest</code>.</li>
</ul>

<p>Here's some code that decodes a CSR and prints out the subject name:</p>

```    string csr = "....";

    char[] characters =
        csr.Replace("-----BEGIN NEW CERTIFICATE REQUEST-----", "")
        .Replace("-----END NEW CERTIFICATE REQUEST-----", "")
        .ToCharArray();

    byte[] csrEncode = Convert.FromBase64CharArray(characters, 0, characters.Length);
    Pkcs10CertificationRequest decodedCsr = new Pkcs10CertificationRequest(csrEncode);
    Console.WriteLine(decodedCsr.GetCertificationRequestInfo().Subject);
```

<p>When I run this code on my CSR above, it writes the following line of output:</p>

<pre class="lang-none prettyprint-override"><code>C=XX,ST=Unknown,L=Nowhere,O=Testers Unlimited,OU=Test,CN=Bob
</code>```

Title: Bouncy Castle Decode CSR c#

Body:
I'm attempting to learn how to decode a csr with the bouncy castle as I intend to use it to learn other crypto things.

I'm also not finding any documentation for c# just java.

Here's how I'm calling DecodeCSR(string str):

 static void Main(string[] args)
    {
        string csr = "-----BEGIN NEW CERTIFICATE REQUEST-----...";
        DecodeCSR(csr);
        Console.ReadLine();
    }

Here's my method where I'm getting an IO Exception(Included below), my main problem is I don't know what to give Pkcs10CertificationRequest.

private static void DecodeCSR(string csr)
    {
        try
        {
            byte[] csrEncode = Encoding.UTF8.GetBytes(csr);
            Pkcs10CertificationRequest csrDecoder = new Pkcs10CertificationRequest(csrEncode);
            byte[] csrDecode = csrDecoder.GetEncoded();
        }
        catch (IOException e)
        {
            Console.WriteLine(e);
        }

    }

The error message:

 System.IO.IOException: unknown tag 13 encountered
   at Org.BouncyCastle.Asn1.Asn1InputStream.BuildObject(Int32 tag, Int32 tagNo, Int32 length)
   at Org.BouncyCastle.Asn1.Asn1InputStream.ReadObject()
   at Org.BouncyCastle.Asn1.Asn1Object.FromByteArray(Byte[] data)
   at Org.BouncyCastle.Pkcs.Pkcs10CertificationRequest..ctor(Byte[] encoded)

Body:
You are trying to decode the CSR into a byte array the wrong way.

Here's a test CSR I created to answer this question:

-----BEGIN NEW CERTIFICATE REQUEST-----
MIIC3zCCAccCAQAwajELMAkGA1UEBhMCWFgxEDAOBgNVBAgTB1Vua25vd24xEDAOBgNVBAcTB05v
d2hlcmUxGjAYBgNVBAoTEVRlc3RlcnMgVW5saW1pdGVkMQ0wCwYDVQQLEwRUZXN0MQwwCgYDVQQD
EwNCb2IwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCUf5kRJVMNwPu+nEnJ3Av5J59H
vkeU0fOQtI+ezvHoJXc0A4iGDBm9PUw+eAXHw237Yu7+AyzgQCD8mwQt/lHLjXG/yeX66PhTFlzH
Lhk4rqL9PQATbl4uCYtWoJmeEOWHL26dfI//AFsL9/smVyjD1mJfee6998PwwHB6BxqSaqXiR1Et
lC4jx+B2E6btvMtREQ94cECoQudSgo3MRMBH+FuEcCofNtwosEpptjIN59ywVfDDU2Me58r930Ej
A8EZbXwYpUjwaHtXK80TKq8yF3Af7Hbt6FhkXOv1QtF0EYUKvE4BVTAx4mPLUy2mct8Ft8/+/Lbt
HDmslaBCAFZrAgMBAAGgMDAuBgkqhkiG9w0BCQ4xITAfMB0GA1UdDgQWBBRt0aHvY5c29iUS6/7E
3FC+Bn3FNDANBgkqhkiG9w0BAQsFAAOCAQEAe+e+3WfxJd/ztcIDRR8YfVkeOlE0b8Erze13fQi/
GsBJQ2MF/7T8x/8ZF2CqusrmLTzb5sY5qVKlRgnguow6xnGu0QOiJdC4kgoqgAaxDwz/eIhMGkt9
hyfTkMWiMD0OfYpdhXWUHrvbzWyUNI1ouWjOoqS03LvSiT4Cq+7Xca8ETVyuBN1FZeFUxO59goqI
eKKenzPqJHcPUjkQbUBgsfKpuRXveRG+vacCt0chWUK4TEVyPzH2EDH0kiQh6dsVizKrHUihh5K/
BhZNqzyBW7G5vbxq4wBz7cLDskfqTsOnHRsAlYmNsXO2wV1LQ2f04F+FHIzZ+IWaO86cxTPMtA==
-----END NEW CERTIFICATE REQUEST-----

To decode a CSR such as this one we need to:

remove the lines -----BEGIN NEW CERTIFICATE REQUEST----- and -----END NEW CERTIFICATE REQUEST----- from the top and bottom,

convert the remaining characters from Base64 into a byte array.

pass the resulting byte array to Pkcs10CertificateRequest.

Here's some code that decodes a CSR and prints out the subject name:

    string csr = "....";

    char[] characters =
        csr.Replace("-----BEGIN NEW CERTIFICATE REQUEST-----", "")
        .Replace("-----END NEW CERTIFICATE REQUEST-----", "")
        .ToCharArray();

    byte[] csrEncode = Convert.FromBase64CharArray(characters, 0, characters.Length);
    Pkcs10CertificationRequest decodedCsr = new Pkcs10CertificationRequest(csrEncode);
    Console.WriteLine(decodedCsr.GetCertificationRequestInfo().Subject);

When I run this code on my CSR above, it writes the following line of output:

C=XX,ST=Unknown,L=Nowhere,O=Testers Unlimited,OU=Test,CN=Bob